<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>Discovery</title>
        <meta name="robots" content="noindex" />


        <!-- Custom HTML head -->
        
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="Discover the world of microcontrollers through Rust">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="favicon.svg">
        <link rel="shortcut icon" href="favicon.png">
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->

    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded affix "><a href="index.html">Introduction</a></li><li class="chapter-item expanded "><a href="01-background/index.html"><strong aria-hidden="true">1.</strong> Background</a></li><li class="chapter-item expanded "><a href="02-requirements/index.html"><strong aria-hidden="true">2.</strong> Hardware/knowledge requirements</a></li><li class="chapter-item expanded "><a href="03-setup/index.html"><strong aria-hidden="true">3.</strong> Setting up a development environment</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="03-setup/linux.html"><strong aria-hidden="true">3.1.</strong> Linux</a></li><li class="chapter-item expanded "><a href="03-setup/windows.html"><strong aria-hidden="true">3.2.</strong> Windows</a></li><li class="chapter-item expanded "><a href="03-setup/macos.html"><strong aria-hidden="true">3.3.</strong> macOS</a></li><li class="chapter-item expanded "><a href="03-setup/verify.html"><strong aria-hidden="true">3.4.</strong> Verify the installation</a></li></ol></li><li class="chapter-item expanded "><a href="04-meet-your-hardware/index.html"><strong aria-hidden="true">4.</strong> Meet your hardware</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="04-meet-your-hardware/microbit-v2.html"><strong aria-hidden="true">4.1.</strong> micro:bit v2</a></li><li class="chapter-item expanded "><a href="04-meet-your-hardware/microbit-v1.html"><strong aria-hidden="true">4.2.</strong> micro:bit v1</a></li><li class="chapter-item expanded "><a href="04-meet-your-hardware/terminology.html"><strong aria-hidden="true">4.3.</strong> Rust Embedded terminology</a></li></ol></li><li class="chapter-item expanded "><a href="05-led-roulette/index.html"><strong aria-hidden="true">5.</strong> LED roulette</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="05-led-roulette/build-it.html"><strong aria-hidden="true">5.1.</strong> Build it</a></li><li class="chapter-item expanded "><a href="05-led-roulette/flash-it.html"><strong aria-hidden="true">5.2.</strong> Flash it</a></li><li class="chapter-item expanded "><a href="05-led-roulette/debug-it.html"><strong aria-hidden="true">5.3.</strong> Debug it</a></li><li class="chapter-item expanded "><a href="05-led-roulette/light-it-up.html"><strong aria-hidden="true">5.4.</strong> Light it up</a></li><li class="chapter-item expanded "><a href="05-led-roulette/it-blinks.html"><strong aria-hidden="true">5.5.</strong> It blinks</a></li><li class="chapter-item expanded "><a href="05-led-roulette/the-challenge.html"><strong aria-hidden="true">5.6.</strong> The challenge</a></li><li class="chapter-item expanded "><a href="05-led-roulette/my-solution.html"><strong aria-hidden="true">5.7.</strong> My solution</a></li></ol></li><li class="chapter-item expanded "><a href="06-serial-communication/index.html"><strong aria-hidden="true">6.</strong> Serial communication</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="06-serial-communication/nix-tooling.html"><strong aria-hidden="true">6.1.</strong> *nix tooling</a></li><li class="chapter-item expanded "><a href="06-serial-communication/windows-tooling.html"><strong aria-hidden="true">6.2.</strong> Windows tooling</a></li></ol></li><li class="chapter-item expanded "><a href="07-uart/index.html"><strong aria-hidden="true">7.</strong> UART</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="07-uart/send-a-single-byte.html"><strong aria-hidden="true">7.1.</strong> Send a single byte</a></li><li class="chapter-item expanded "><a href="07-uart/send-a-string.html"><strong aria-hidden="true">7.2.</strong> Send a string</a></li><li class="chapter-item expanded "><a href="07-uart/naive-approch-write.html"><strong aria-hidden="true">7.3.</strong> Naive approach and write!</a></li><li class="chapter-item expanded "><a href="07-uart/receive-a-single-byte.html"><strong aria-hidden="true">7.4.</strong> Receive a single byte</a></li><li class="chapter-item expanded "><a href="07-uart/echo-server.html"><strong aria-hidden="true">7.5.</strong> Echo server</a></li><li class="chapter-item expanded "><a href="07-uart/reverse-a-string.html"><strong aria-hidden="true">7.6.</strong> Reverse a string</a></li><li class="chapter-item expanded "><a href="07-uart/my-solution.html"><strong aria-hidden="true">7.7.</strong> My solution</a></li></ol></li><li class="chapter-item expanded "><a href="08-i2c/index.html"><strong aria-hidden="true">8.</strong> I2C</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="08-i2c/the-general-protocol.html"><strong aria-hidden="true">8.1.</strong> The general protocol</a></li><li class="chapter-item expanded "><a href="08-i2c/lsm303agr.html"><strong aria-hidden="true">8.2.</strong> LSM303AGR</a></li><li class="chapter-item expanded "><a href="08-i2c/read-a-single-register.html"><strong aria-hidden="true">8.3.</strong> Read a single register</a></li><li class="chapter-item expanded "><a href="08-i2c/using-a-driver.html"><strong aria-hidden="true">8.4.</strong> Using a driver</a></li><li class="chapter-item expanded "><a href="08-i2c/the-challenge.html"><strong aria-hidden="true">8.5.</strong> The challenge</a></li><li class="chapter-item expanded "><a href="08-i2c/my-solution.html"><strong aria-hidden="true">8.6.</strong> My solution</a></li></ol></li><li class="chapter-item expanded "><a href="09-led-compass/index.html"><strong aria-hidden="true">9.</strong> LED compass</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="09-led-compass/calibration.html"><strong aria-hidden="true">9.1.</strong> Calibration</a></li><li class="chapter-item expanded "><a href="09-led-compass/take-1.html"><strong aria-hidden="true">9.2.</strong> Take 1</a></li><li class="chapter-item expanded "><a href="09-led-compass/solution-1.html"><strong aria-hidden="true">9.3.</strong> Solution 1</a></li><li class="chapter-item expanded "><a href="09-led-compass/take-2.html"><strong aria-hidden="true">9.4.</strong> Take 2</a></li><li class="chapter-item expanded "><a href="09-led-compass/solution-2.html"><strong aria-hidden="true">9.5.</strong> Solution 2</a></li><li class="chapter-item expanded "><a href="09-led-compass/magnitude.html"><strong aria-hidden="true">9.6.</strong> Magnitude</a></li></ol></li><li class="chapter-item expanded "><a href="10-punch-o-meter/index.html"><strong aria-hidden="true">10.</strong> Punch-o-meter</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="10-punch-o-meter/gravity-is-up.html"><strong aria-hidden="true">10.1.</strong> Gravity is up?</a></li><li class="chapter-item expanded "><a href="10-punch-o-meter/the-challenge.html"><strong aria-hidden="true">10.2.</strong> The challenge</a></li><li class="chapter-item expanded "><a href="10-punch-o-meter/my-solution.html"><strong aria-hidden="true">10.3.</strong> My solution</a></li></ol></li><li class="chapter-item expanded "><a href="explore.html"><strong aria-hidden="true">11.</strong> What's left for you to explore</a></li><li class="spacer"></li><li class="chapter-item expanded affix "><a href="appendix/1-general-troubleshooting/index.html">General troubleshooting</a></li><li class="chapter-item expanded affix "><a href="appendix/2-how-to-use-gdb/index.html">How to use GDB</a></li><li class="spacer"></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Discovery</h1>

                    <div class="right-buttons">
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>
                        <a href="https://github.com/rust-embedded/discovery/" title="Git repository" aria-label="Git repository">
                            <i id="git-repository-button" class="fa fa-github"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="discovery"><a class="header" href="#discovery">Discovery</a></h1>
<blockquote>
<p>Discover the world of microcontrollers through <a href="https://www.rust-lang.org/">Rust</a>!</p>
</blockquote>
<p>This book is an introductory course on microcontroller-based embedded systems that uses Rust as the
teaching language rather than the usual C/C++.</p>
<h2 id="scope"><a class="header" href="#scope">Scope</a></h2>
<p>The following topics will be covered (eventually, I hope):</p>
<ul>
<li>
<p>How to write, build, flash and debug an &quot;embedded&quot; (Rust) program.</p>
</li>
<li>
<p>Functionality (&quot;peripherals&quot;) commonly found in microcontrollers: Digital input and output, Pulse
Width Modulation (PWM), Analog to Digital Converters (ADC), common communication protocols like
Serial, I2C and SPI, etc.</p>
</li>
<li>
<p>Multitasking concepts: cooperative vs preemptive multitasking, interrupts, schedulers, etc.</p>
</li>
<li>
<p>Control systems concepts: sensors, calibration, digital filters, actuators, open loop control,
closed loop control, etc.</p>
</li>
</ul>
<h2 id="approach"><a class="header" href="#approach">Approach</a></h2>
<ul>
<li>
<p>Beginner friendly. No previous experience with microcontrollers or embedded systems is required.</p>
</li>
<li>
<p>Hands on. Plenty of exercises to put the theory into practice. <em>You</em> will be doing most of the
work here.</p>
</li>
<li>
<p>Tool centered. We'll make plenty use of tooling to ease development. &quot;Real&quot; debugging, with GDB,
and logging will be introduced early on. Using LEDs as a debugging mechanism has no place here.</p>
</li>
</ul>
<h2 id="non-goals"><a class="header" href="#non-goals">Non-goals</a></h2>
<p>What's out of scope for this book:</p>
<ul>
<li>
<p>Teaching Rust. There's plenty of material on that topic already. We'll focus on microcontrollers
and embedded systems.</p>
</li>
<li>
<p>Being a comprehensive text about electric circuit theory or electronics. We'll just cover the
minimum required to understand how some devices work.</p>
</li>
<li>
<p>Covering details such as linker scripts and the boot process. For example, we'll use existing tools
to help get your code onto your board, but not go into detail about how those tools work.</p>
</li>
</ul>
<p>Also I don't intend to port this material to other development boards; this book will make exclusive
use of the micro:bit development board.</p>
<h2 id="reporting-problems"><a class="header" href="#reporting-problems">Reporting problems</a></h2>
<p>The source of this book is in <a href="https://github.com/rust-embedded/discovery">this repository</a>. If you encounter any typo or problem with the code
report it on the <a href="https://github.com/rust-embedded/discovery/issues">issue tracker</a>.</p>
<h2 id="other-embedded-rust-resources"><a class="header" href="#other-embedded-rust-resources">Other embedded Rust resources</a></h2>
<p>This Discovery book is just one of several embedded Rust resources provided by the
<a href="https://github.com/rust-embedded/wg">Embedded Working Group</a>. The full selection can be found at <a href="https://docs.rust-embedded.org">The Embedded Rust Bookshelf</a>. This
includes the list of <a href="https://docs.rust-embedded.org/faq.html">Frequently Asked Questions</a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="background"><a class="header" href="#background">Background</a></h1>
<h2 id="whats-a-microcontroller"><a class="header" href="#whats-a-microcontroller">What's a microcontroller?</a></h2>
<p>A microcontroller is a <em>system</em> on a chip. Whereas your computer is made up of several discrete
components: a processor, RAM, storage, an Ethernet port, etc.; a microcontroller has all those types
of components built into a single &quot;chip&quot; or package. This makes it possible to build systems with
fewer parts.</p>
<h2 id="what-can-you-do-with-a-microcontroller"><a class="header" href="#what-can-you-do-with-a-microcontroller">What can you do with a microcontroller?</a></h2>
<p>Lots of things! Microcontrollers are the central part of what are known as &quot;<em>embedded</em> systems&quot;.
Embedded systems are everywhere, but you don't usually notice them. They control the machines that
wash your clothes, print your documents, and cook your food. Embedded systems keep the buildings
that you live and work in at a comfortable temperature, and control the components that make the
vehicles you travel in stop and go.</p>
<p>Most embedded systems operate without user intervention. Even if they expose a user interface like a
washing machine does; most of their operation is done on their own.</p>
<p>Embedded systems are often used to <em>control</em> a physical process. To make this possible, they have
one or more devices to tell them about the state of the world (&quot;sensors&quot;), and one or more
devices which allow them to change things (&quot;actuators&quot;). For example, a building climate control
system might have:</p>
<ul>
<li>Sensors which measure temperature and humidity in various locations.</li>
<li>Actuators which control the speed of fans.</li>
<li>Actuators which cause heat to be added or removed from the building.</li>
</ul>
<h2 id="when-should-i-use-a-microcontroller"><a class="header" href="#when-should-i-use-a-microcontroller">When should I use a microcontroller?</a></h2>
<p>Many of the embedded systems listed above could be implemented with a computer running Linux (for
example a &quot;Raspberry Pi&quot;). Why use a microcontroller instead? Sounds like it might be harder to
develop a program.</p>
<p>Some reasons might include:</p>
<p><strong>Cost.</strong> A microcontroller is much cheaper than a general purpose computer. Not only is the
microcontroller cheaper; it also requires many fewer external electrical components to operate.
This makes Printed Circuit Boards (PCB) smaller and cheaper to design and manufacture.</p>
<p><strong>Power consumption.</strong> Most microcontrollers consume a fraction of the power of a full blown
processor. For applications which run on batteries, that makes a huge difference.</p>
<p><strong>Responsiveness.</strong> To accomplish their purpose, some embedded systems must always react within a
limited time interval (e.g. the &quot;anti-lock&quot; braking system of a car). If the system misses this
type of <em>deadline</em>, a catastrophic failure might occur. Such a deadline is called a &quot;hard real time&quot;
requirement. An embedded system which is bound by such a deadline is referred to as a &quot;hard
real-time system&quot;. A general purpose computer and OS usually has many software components which
share the computer's processing resources. This makes it harder to guarantee execution of a program
within tight time constraints.</p>
<p><strong>Reliability.</strong> In systems with fewer components (both hardware and software), there is less to go
wrong!</p>
<h2 id="when-should-i-not-use-a-microcontroller"><a class="header" href="#when-should-i-not-use-a-microcontroller">When should I <em>not</em> use a microcontroller?</a></h2>
<p>Where heavy computations are involved. To keep their power consumption low, microcontrollers have
very limited computational resources available to them. For example, some microcontrollers don't
even have hardware support for floating point operations. On those devices, performing a simple
addition of single precision numbers can take hundreds of CPU cycles.</p>
<h2 id="why-use-rust-and-not-c"><a class="header" href="#why-use-rust-and-not-c">Why use Rust and not C?</a></h2>
<p>Hopefully, I don't need to convince you here as you are probably familiar with the language
differences between Rust and C. One point I do want to bring up is package management. C lacks an
official, widely accepted package management solution whereas Rust has Cargo. This makes development
<em>much</em> easier. And, IMO, easy package management encourages code reuse because libraries can be
easily integrated into an application which is also a good thing as libraries get more &quot;battle
testing&quot;.</p>
<h2 id="why-should-i-not-use-rust"><a class="header" href="#why-should-i-not-use-rust">Why should I not use Rust?</a></h2>
<p>Or why should I prefer C over Rust?</p>
<p>The C ecosystem is way more mature. Off the shelf solutions for several problems already exist. If
you need to control a time sensitive process, you can grab one of the existing commercial Real Time
Operating Systems (RTOS) out there and solve your problem. There are no commercial, production-grade
RTOSes in Rust yet so you would have to either create one yourself or try one of the ones that are
in development. You can find a list of those in the <a href="https://github.com/rust-embedded/awesome-embedded-rust#real-time-operating-system-rtos">Awesome Embedded Rust</a> repository.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="hardwareknowledge-requirements"><a class="header" href="#hardwareknowledge-requirements">Hardware/knowledge requirements</a></h1>
<p>The primary knowledge requirement to read this book is to know <em>some</em> Rust. It's
hard for me to quantify <em>some</em> but at least I can tell you that you don't need
to fully grok generics, but you do need to know how to <em>use</em> closures. You also
need to be familiar with the idioms of the <a href="https://rust-lang-nursery.github.io/edition-guide/">2018 edition</a>, in particular with
the fact that <code>extern crate</code> is not necessary in the 2018 edition.</p>
<p>Also, to follow this material you'll need the following hardware:</p>
<ul>
<li>A <a href="https://tech.microbit.org/hardware/">micro:bit v2</a> board, alternatively a <a href="https://tech.microbit.org/hardware/1-5-revision/">micro:bit v1.5</a> board, the book
will refer to the v1.5 as just v1.</li>
</ul>
<p>(You can purchase this board from several <a href="https://microbit.org/buy/">electronics</a> <a href="https://www.mouser.com/microbit/_/N-aez3t?P=1y8um0l">suppliers</a>)</p>
<p align="center">
<img title="micro:bit" src="02-requirements/../assets/microbit-v2.jpg">
</p>
<blockquote>
<p><strong>NOTE</strong> This is an image of a micro:bit v2, the front of the v1 looks slightly different</p>
</blockquote>
<ul>
<li>One micro-B USB cable, required to make the micro:bit board work.
Make sure that the cable supports data transfer as some cables only support charging devices.</li>
</ul>
<p align="center">
<img title="micro-B USB cable" src="02-requirements/../assets/usb-cable.jpg">
</p>
<blockquote>
<p><strong>NOTE</strong> You may already have a cable like this, as some micro:bit kits ship with such cables.
Some USB cables used to charge mobile devices may also work, if they are micro-B and have the
capability to transmit data.</p>
</blockquote>
<blockquote>
<p><strong>FAQ</strong>: Wait, why do I need this specific hardware?</p>
</blockquote>
<p>It makes my life and yours much easier.</p>
<p>The material is much, much more approachable if we don't have to worry about hardware differences.
Trust me on this one.</p>
<blockquote>
<p><strong>FAQ</strong>: Can I follow this material with a different development board?</p>
</blockquote>
<p>Maybe? It depends mainly on two things: your previous experience with microcontrollers and/or
whether a high level crate already exists, like the <a href="https://docs.rs/nrf52-hal"><code>nrf52-hal</code></a>, for your development board
somewhere. You can look through the <a href="https://github.com/rust-embedded/awesome-embedded-rust#hal-implementation-crates">Awesome Embedded Rust HAL list</a> for your microcontroller,
if you intend to use a different one.</p>
<p>With a different development board, this text would lose most if not all its beginner friendliness
and &quot;easy to follow&quot;-ness, IMO.</p>
<p>If you have a different development board and you don't consider yourself a total beginner, you are
better off starting with the <a href="https://rust-embedded.github.io/cortex-m-quickstart/cortex_m_quickstart/">quickstart</a> project template.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="setting-up-a-development-environment"><a class="header" href="#setting-up-a-development-environment">Setting up a development environment</a></h1>
<p>Dealing with microcontrollers involves several tools as we'll be dealing with an architecture
different from your computer's and we'll have to run and debug programs on a &quot;remote&quot; device.</p>
<h2 id="documentation"><a class="header" href="#documentation">Documentation</a></h2>
<p>Tooling is not everything though. Without documentation, it is pretty much impossible to work with
microcontrollers.</p>
<p>We'll be referring to all these documents throughout this book:</p>
<ul>
<li><a href="https://www.st.com/resource/en/datasheet/lsm303agr.pdf">LSM303AGR</a></li>
</ul>
<h2 id="tools"><a class="header" href="#tools">Tools</a></h2>
<p>We'll use all the tools listed below. Where a minimum version is not specified, any recent version
should work but we have listed the version we have tested.</p>
<ul>
<li>
<p>Rust 1.57.0 or a newer toolchain.</p>
</li>
<li>
<p><code>gdb-multiarch</code>. Tested version: 10.2. Other versions will most likely work as well though
If your distribution/platform does not have <code>gdb-multiarch</code> available <code>arm-none-eabi-gdb</code>
will do the trick as well. Furthermore, some normal <code>gdb</code> binaries are built with multiarch
capabilities as well, you can find further information about this in the sub chapters.</p>
</li>
<li>
<p><a href="https://github.com/rust-embedded/cargo-binutils"><code>cargo-binutils</code></a>. Version 0.3.3 or newer.</p>
</li>
</ul>
<ul>
<li><a href="https://github.com/probe-rs/cargo-embed"><code>cargo-embed</code></a>. Version 0.11.0 or newer.</li>
</ul>
<ul>
<li>
<p><code>minicom</code> on Linux and macOS. Tested version: 2.7.1. Other versions will most likely work as well though</p>
</li>
<li>
<p><code>PuTTY</code> on Windows.</p>
</li>
</ul>
<p>Next, follow OS-agnostic installation instructions for a few of the tools:</p>
<h3 id="rustc--cargo"><a class="header" href="#rustc--cargo"><code>rustc</code> &amp; Cargo</a></h3>
<p>Install rustup by following the instructions at <a href="https://rustup.rs">https://rustup.rs</a>.</p>
<p>If you already have rustup installed double check that you are on the stable
channel and your stable toolchain is up-to-date. <code>rustc -V</code> should return a date
newer than the one shown below:</p>
<pre><code class="language-console">$ rustc -V
rustc 1.53.0 (53cb7b09b 2021-06-17)
</code></pre>
<h3 id="cargo-binutils"><a class="header" href="#cargo-binutils"><code>cargo-binutils</code></a></h3>
<pre><code class="language-console">$ rustup component add llvm-tools-preview

$ cargo install cargo-binutils --vers 0.3.3

$ cargo size --version
cargo-size 0.3.3
</code></pre>
<h3 id="cargo-embed"><a class="header" href="#cargo-embed"><code>cargo-embed</code></a></h3>
<pre><code class="language-console">$ cargo install cargo-embed --vers 0.11.0

$ cargo embed --version
cargo-embed 0.11.0
git commit: crates.io
</code></pre>
<h3 id="this-repository"><a class="header" href="#this-repository">This repository</a></h3>
<p>Since this book also contains some small Rust code bases used in various chapters
you will also have to download its source code. You can do this in one of the following ways:</p>
<ul>
<li>Visit the <a href="https://github.com/rust-embedded/discovery/">repository</a>, click the green &quot;Code&quot; button and then the
&quot;Download Zip&quot; one</li>
<li>Clone it using git (if you know git you presumably already have it installed) from the same repository as linked in
the zip approach</li>
</ul>
<h3 id="os-specific-instructions"><a class="header" href="#os-specific-instructions">OS specific instructions</a></h3>
<p>Now follow the instructions specific to the OS you are using:</p>
<ul>
<li><a href="03-setup/linux.html">Linux</a></li>
<li><a href="03-setup/windows.html">Windows</a></li>
<li><a href="03-setup/macos.html">macOS</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="linux"><a class="header" href="#linux">Linux</a></h1>
<p>Here are the installation commands for a few Linux distributions.</p>
<h2 id="ubuntu-2004-or-newer--debian-10-or-newer"><a class="header" href="#ubuntu-2004-or-newer--debian-10-or-newer">Ubuntu 20.04 or newer / Debian 10 or newer</a></h2>
<blockquote>
<p><strong>NOTE</strong> <code>gdb-multiarch</code> is the GDB command you'll use to debug your ARM
Cortex-M programs</p>
</blockquote>
<pre><code class="language-console">$ sudo apt-get install \
  gdb-multiarch \
  minicom
</code></pre>
<h2 id="fedora-32-or-newer"><a class="header" href="#fedora-32-or-newer">Fedora 32 or newer</a></h2>
<blockquote>
<p><strong>NOTE</strong> <code>gdb</code> is the GDB command you'll use to debug your ARM
Cortex-M programs</p>
</blockquote>
<pre><code class="language-console">$ sudo dnf install \
  gdb \
  minicom
</code></pre>
<h2 id="arch-linux"><a class="header" href="#arch-linux">Arch Linux</a></h2>
<blockquote>
<p><strong>NOTE</strong> <code>arm-none-eabi-gdb</code> is the GDB command you'll use to debug your ARM
Cortex-M programs</p>
</blockquote>
<pre><code class="language-console">$ sudo pacman -S \
  arm-none-eabi-gdb \
  minicom
</code></pre>
<h2 id="other-distros"><a class="header" href="#other-distros">Other distros</a></h2>
<blockquote>
<p><strong>NOTE</strong> <code>arm-none-eabi-gdb</code> is the GDB command you'll use to debug your ARM
Cortex-M programs</p>
</blockquote>
<p>For distros that don't have packages for <a href="https://developer.arm.com/open-source/gnu-toolchain/gnu-rm/downloads">ARM's pre-built
toolchain</a>,
download the &quot;Linux 64-bit&quot; file and put its <code>bin</code> directory on your path.
Here's one way to do it:</p>
<pre><code class="language-console">$ mkdir -p ~/local &amp;&amp; cd ~/local
$ tar xjf /path/to/downloaded/file/gcc-arm-none-eabi-9-2020-q2-update-x86_64-linux.tar.bz2
</code></pre>
<p>Then, use your editor of choice to append to your <code>PATH</code> in the appropriate
shell init file (e.g. <code>~/.zshrc</code> or <code>~/.bashrc</code>):</p>
<pre><code>PATH=$PATH:$HOME/local/gcc-arm-none-eabi-9-2020-q2-update/bin
</code></pre>
<h2 id="udev-rules"><a class="header" href="#udev-rules">udev rules</a></h2>
<p>These rules let you use USB devices like the micro:bit without root privilege, i.e. <code>sudo</code>.</p>
<p>Create this file in <code>/etc/udev/rules.d</code> with the content shown below.</p>
<pre><code class="language-console">$ cat /etc/udev/rules.d/99-microbit.rules
</code></pre>
<pre><code class="language-text"># CMSIS-DAP for microbit
SUBSYSTEM==&quot;usb&quot;, ATTR{idVendor}==&quot;0d28&quot;, ATTR{idProduct}==&quot;0204&quot;, MODE:=&quot;666&quot;
</code></pre>
<p>Then reload the udev rules with:</p>
<pre><code class="language-console">$ sudo udevadm control --reload-rules
</code></pre>
<p>If you had any board plugged to your computer, unplug them and then plug them in again.</p>
<p>Now, go to the <a href="03-setup/verify.html">next section</a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="windows"><a class="header" href="#windows">Windows</a></h1>
<h2 id="arm-none-eabi-gdb"><a class="header" href="#arm-none-eabi-gdb"><code>arm-none-eabi-gdb</code></a></h2>
<p>ARM provides <code>.exe</code> installers for Windows. Grab one from <a href="https://developer.arm.com/open-source/gnu-toolchain/gnu-rm/downloads">here</a>, and follow the instructions.
Just before the installation process finishes tick/select the &quot;Add path to environment variable&quot;
option. Then verify that the tools are in your <code>%PATH%</code>:</p>
<pre><code class="language-console">$ arm-none-eabi-gcc -v
(..)
gcc version 5.4.1 20160919 (release) (..)
</code></pre>
<h2 id="putty"><a class="header" href="#putty">PuTTY</a></h2>
<p>Download the latest <code>putty.exe</code> from <a href="http://www.chiark.greenend.org.uk/%7Esgtatham/putty/download.html">this site</a> and place it somewhere in your <code>%PATH%</code>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="macos"><a class="header" href="#macos">macOS</a></h1>
<p>All the tools can be installed using <a href="http://brew.sh/">Homebrew</a>:</p>
<pre><code class="language-console">$ # Arm GCC toolchain
$ brew tap ArmMbed/homebrew-formulae
$ brew install arm-none-eabi-gcc

$ # Minicom
$ brew install minicom
</code></pre>
<p>That's all! Go to the <a href="03-setup/verify.html">next section</a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="verify-the-installation"><a class="header" href="#verify-the-installation">Verify the installation</a></h1>
<p>Let's verify that all the tools were installed correctly.</p>
<h2 id="linux-only"><a class="header" href="#linux-only">Linux only</a></h2>
<h3 id="verify-permissions"><a class="header" href="#verify-permissions">Verify permissions</a></h3>
<p>Connect the micro:bit to your computer using a USB cable.</p>
<p>The micro:bit should now appear as a USB device (file) in <code>/dev/bus/usb</code>. Let's find out how it got
enumerated:</p>
<pre><code class="language-console">$ lsusb | grep -i &quot;NXP ARM mbed&quot;
Bus 001 Device 065: ID 0d28:0204 NXP ARM mbed
$ # ^^^        ^^^
</code></pre>
<p>In my case, the micro:bit got connected to the bus #1 and got enumerated as the device #65. This means the
file <code>/dev/bus/usb/001/065</code> <em>is</em> the micro:bit. Let's check its permissions:</p>
<pre><code class="language-console">$ ls -l /dev/bus/usb/001/065
crw-rw-rw-. 1 root root 189, 64 Sep  5 14:27 /dev/bus/usb/001/065
</code></pre>
<p>The permissions should be <code>crw-rw-rw-</code>. If it's not ... then check your <a href="03-setup/linux.html#udev-rules">udev
rules</a> and try re-loading them with:</p>
<pre><code class="language-console">$ sudo udevadm control --reload-rules
</code></pre>
<h1 id="all"><a class="header" href="#all">All</a></h1>
<h2 id="verifying-cargo-embed"><a class="header" href="#verifying-cargo-embed">Verifying cargo-embed</a></h2>
<p>First, connect the micro:bit to your Computer using a USB cable.</p>
<p>At least an orange LED right next to the USB port of the micro:bit should light up.
Furthermore, if you have never flashed another program on to your micro:bit, the default
program the micro:bit ships with should start blinking the red LEDs on its back, you
can ignore them.</p>
<p>Next up you will have to modify <code>Embed.toml</code> in the <code>src/03-setup</code> directory of the
book's source code. In the <code>default.general</code> section you will find two commented out
chip variants:</p>
<pre><code class="language-toml">[default.general]
# chip = &quot;nrf52833_xxAA&quot; # uncomment this line for micro:bit V2
# chip = &quot;nrf51822_xxAA&quot; # uncomment this line for micro:bit V1
</code></pre>
<p>If you are working with the micro:bit v2 board uncomment the first, for the v1
uncomment the second line.</p>
<p>Next run one of these commands:</p>
<pre><code>$ # make sure you are in src/03-setup of the books source code
$ # If you are working with micro:bit v2
$ rustup target add thumbv7em-none-eabihf
$ cargo embed --target thumbv7em-none-eabihf

$ # If you are working with micro:bit v1
$ rustup target add thumbv6m-none-eabi
$ cargo embed --target thumbv6m-none-eabi
</code></pre>
<p>If everything works correctly cargo-embed should first compile the small example program
in this directory, then flash it and finally open a nice text based user interface that
prints Hello World.</p>
<p>(If it does not, check out <a href="03-setup/../appendix/1-general-troubleshooting/index.html">general troubleshooting</a> instructions.)</p>
<p>This output is coming from the small Rust program you just flashed on to your micro:bit.
Everything is working properly and you can continue with the next chapters!</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="meet-your-hardware"><a class="header" href="#meet-your-hardware">Meet your hardware</a></h1>
<p>Let's get familiar with the hardware we'll be working with.</p>
<h2 id="microbit"><a class="header" href="#microbit">micro:bit</a></h2>
<p align="center">
<img title="micro:bit" src="04-meet-your-hardware/../assets/microbit-v2.jpg">
</p>
<p>Here are some of the many components on the board:</p>
<ul>
<li>A <a href="https://en.wikipedia.org/wiki/Microcontroller">microcontroller</a>.</li>
<li>A number of LEDs, most notably the LED matrix on the back</li>
<li>Two user buttons as well as a reset button (the one next to the USB port).</li>
<li>One USB port.</li>
<li>A sensor that is both a <a href="https://en.wikipedia.org/wiki/Magnetometer">magnetometer</a> and an <a href="https://en.wikipedia.org/wiki/Accelerometer">accelerometer</a></li>
</ul>
<p>Of these components, the most important is the microcontroller (sometimes
shortened to &quot;MCU&quot; for &quot;microcontroller unit&quot;), which is the bigger of the two
black squares sitting on the side of the board with the USB port. The MCU is
what runs your code. You might sometimes read about &quot;programming a board&quot;, when
in reality what we are doing is programming the MCU that is installed on the board.</p>
<p>If you happen to be interested in a more in detail description of the board you
can checkout the <a href="https://tech.microbit.org/hardware/">micro:bit website</a>.</p>
<p>Since the MCU is so important, let's take a closer look at the one sitting on our board.
Note that only one of the following two sections applies to your board, depending on whether
you are working with a micro:bit v2 or v1.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="nordic-nrf52833-the-nrf52-microbit-v2"><a class="header" href="#nordic-nrf52833-the-nrf52-microbit-v2">Nordic nRF52833 (the &quot;nRF52&quot;, micro:bit v2)</a></h1>
<p>Our MCU has 73 tiny metal <strong>pins</strong> sitting right underneath it (it's a so called <a href="https://en.wikipedia.org/wiki/Flat_no-leads_package">aQFN73</a> chip).
These pins are connected to <strong>traces</strong>, the little &quot;roads&quot; that act as the wires connecting components
together on the board. The MCU can dynamically alter the electrical properties
of the pins. This works similar to a light switch altering how electrical
current flows through a circuit. By enabling or disabling electrical current to
flow through a specific pin, an LED attached to that pin (via the traces) can
be turned on and off.</p>
<p>Each manufacturer uses a different part numbering scheme, but many will allow
you to determine information about a component simply by looking at the part
number. Looking at our MCU's part number (<code>N52833 QIAAA0 2024AL</code>, you probably cannot
see it with your bare eye, but it is on the chip), the <code>n</code> at the
front hints to us that this is a part manufactured by <a href="https://www.nordicsemi.com/">Nordic Semiconductor</a>.
Looking up the part number on their website we quickly find the <a href="https://www.nordicsemi.com/products/nrf52833">product page</a>.
There we learn that our chip's main marketing point is that it is a
&quot;Bluetooth Low Energy and 2.4 GHz SoC&quot; (SoC being short for &quot;System on a Chip&quot;),
which explains the RF in the product name since RF is short for radio frequency.
If we search through the documentation of the chip linked on the <a href="https://www.nordicsemi.com/products/nrf52833">product page</a>
for a bit we find the <a href="https://infocenter.nordicsemi.com/pdf/nRF52833_PS_v1.3.pdf">product specification</a> which contains chapter 10 &quot;Ordering Information&quot;
dedicated to explaining the weird chip naming. Here we learn that:</p>
<ul>
<li>The <code>N52</code> is the MCU's series, indicating that there are other <code>nRF52</code> MCUs</li>
<li>The <code>833</code> is the part code</li>
<li>The <code>QI</code> is the package code, short for <code>aQFN73</code></li>
<li>The <code>AA</code> is the variant code, indicating how much RAM and flash memory the MCU has,
in our case 512 kilobyte flash and 128 kilobyte RAM</li>
<li>The <code>A0</code> is the build code, indicating the hardware version (<code>A</code>) as well as the product configuration (<code>0</code>)</li>
<li>The <code>2024AL</code> is a tracking code, hence it might differ on your chip</li>
</ul>
<p>The product specification does of course contain a lot more useful information about
the chip, for example that it is based on an ARM® Cortex™-M4 32-bit processor.</p>
<h2 id="arm-cortex-m4"><a class="header" href="#arm-cortex-m4">Arm? Cortex-M4?</a></h2>
<p>If our chip is manufactured by Nordic, then who is Arm? And if our chip is the
nRF52833, what is the Cortex-M4?</p>
<p>You might be surprised to hear that while &quot;Arm-based&quot; chips are quite
popular, the company behind the &quot;Arm&quot; trademark (<a href="https://www.arm.com/">Arm Holdings</a>) doesn't
actually manufacture chips for purchase. Instead, their primary business
model is to just <em>design</em> parts of chips. They will then license those designs to
manufacturers, who will in turn implement the designs (perhaps with some of
their own tweaks) in the form of physical hardware that can then be sold.
Arm's strategy here is different from companies like Intel, which both
designs <em>and</em> manufactures their chips.</p>
<p>Arm licenses a bunch of different designs. Their &quot;Cortex-M&quot; family of designs
are mainly used as the core in microcontrollers. For example, the Cortex-M4
(the core our chip is based on) is designed for low cost and low power usage.
The Cortex-M7 is higher cost, but with more features and performance.</p>
<p>Luckily, you don't need to know too much about different types of processors
or Cortex designs for the sake of this book. However, you are hopefully now a
bit more knowledgeable about the terminology of your device. While you are
working specifically with an nRF52833, you might find yourself reading
documentation and using tools for Cortex-M-based chips, as the nRF52833 is
based on a Cortex-M design.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="nordic-nrf51822-the-nrf51-microbit-v1"><a class="header" href="#nordic-nrf51822-the-nrf51-microbit-v1">Nordic nRF51822 (the &quot;nRF51&quot;, micro:bit v1)</a></h1>
<p>Our MCU has 48 tiny metal <strong>pins</strong> sitting right underneath it (it's a so called <a href="https://en.wikipedia.org/wiki/Flat_no-leads_package">QFN48</a> chip).
These pins are connected to <strong>traces</strong>, the little &quot;roads&quot; that act as the wires connecting components
together on the board. The MCU can dynamically alter the electrical properties
of the pins. This works similar to a light switch altering how electrical
current flows through a circuit. By enabling or disabling electrical current to
flow through a specific pin, an LED attached to that pin (via the traces) can
be turned on and off.</p>
<p>Each manufacturer uses a different part numbering scheme, but many will allow
you to determine information about a component simply by looking at the part
number. Looking at our MCU's part number (<code>N51822 QFAAH3 1951LN</code>, you probably cannot
see it with your bare eye, but it is on the chip), the <code>n</code> at the
front hints to us that this is a part manufactured by <a href="https://www.nordicsemi.com/">Nordic Semiconductor</a>.
Looking up the part number on their website we quickly find the <a href="https://www.nordicsemi.com/products/nrf51822">product page</a>.
There we learn that our chip's main marketing point is that it is a
&quot;Bluetooth Low Energy and 2.4 GHz SoC&quot; (SoC being short for &quot;System on a Chip&quot;),
which explains the RF in the product name since RF is short for radio frequency.
If we search through the documentation of the chip linked on the <a href="https://www.nordicsemi.com/products/nrf51822">product page</a>
for a bit we find the <a href="https://infocenter.nordicsemi.com/pdf/nRF51822_PS_v3.3.pdf">product specification</a> which contains chapter 10 &quot;Ordering Information&quot;
dedicated to explaining the weird chip naming. Here we learn that:</p>
<ul>
<li>The <code>N51</code> is the MCU's series, indicating that there are other <code>nRF51</code> MCUs</li>
<li>The <code>822</code> is the part code</li>
<li>The <code>QF</code> is the package code, in this case short for <code>QFN48</code></li>
<li>The <code>AA</code> is the variant code, indicating how much RAM and flash memory the MCU has,
in our case 256 kilobyte flash and 16 kilobyte RAM</li>
<li>The <code>H3</code> is the build code, indicating the hardware version (<code>H</code>) as well as the product configuration (<code>3</code>)</li>
<li>The <code>1951LN</code> is a tracking code, hence it might differ on your chip</li>
</ul>
<p>The product specification does of course contain a lot more useful information about
the chip, for example that it is based on an ARM® Cortex™-M0 32-bit processor.</p>
<h3 id="arm-cortex-m0"><a class="header" href="#arm-cortex-m0">Arm? Cortex-M0?</a></h3>
<p>If our chip is manufactured by Nordic, then who is Arm? And if our chip is the
nRF51822, what is the Cortex-M0?</p>
<p>You might be surprised to hear that while &quot;Arm-based&quot; chips are quite
popular, the company behind the &quot;Arm&quot; trademark (<a href="https://www.arm.com/">Arm Holdings</a>) doesn't
actually manufacture chips for purchase. Instead, their primary business
model is to just <em>design</em> parts of chips. They will then license those designs to
manufacturers, who will in turn implement the designs (perhaps with some of
their own tweaks) in the form of physical hardware that can then be sold.
Arm's strategy here is different from companies like Intel, which both
designs <em>and</em> manufactures their chips.</p>
<p>Arm licenses a bunch of different designs. Their &quot;Cortex-M&quot; family of designs
are mainly used as the core in microcontrollers. For example, the Cortex-M0
(the core our chip is based on) is designed for low cost and low power usage.
The Cortex-M7 is higher cost, but with more features and performance.</p>
<p>Luckily, you don't need to know too much about different types of processors
or Cortex designs for the sake of this book. However, you are hopefully now a
bit more knowledgeable about the terminology of your device. While you are
working specifically with an nRF51822, you might find yourself reading
documentation and using tools for Cortex-M-based chips, as the nRF51822 is
based on a Cortex-M design.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="rust-embedded-terminology"><a class="header" href="#rust-embedded-terminology">Rust Embedded terminology</a></h1>
<p>Before we dive into programming the micro:bit let's have a quick look
at the libraries and terminology that will be important for all the
future chapters.</p>
<h2 id="abstraction-layers"><a class="header" href="#abstraction-layers">Abstraction layers</a></h2>
<p>For any fully supported microcontroller/board with a microcontroller
you will usually hear the following terms being used for their levels
of abstraction:</p>
<h3 id="peripheral-access-crate-pac"><a class="header" href="#peripheral-access-crate-pac">Peripheral Access Crate (PAC)</a></h3>
<p>The job of the PAC is to provide a safe (ish) direct interface to the
peripherals of the chip, allowing you to configure
every last bit however you want (of course also in wrong ways). Usually
you only ever have to deal with the PAC if either the layers that are
higher up don't fulfill your needs or when you are developing them.
The PAC we are (implicitly) going to use is either the one for the <a href="https://crates.io/crates/nrf52833-pac">nRF52</a>
or for the <a href="https://crates.io/crates/nrf51">nRF51</a>.</p>
<h3 id="the-hardware-abstraction-layer-hal"><a class="header" href="#the-hardware-abstraction-layer-hal">The Hardware Abstraction Layer (HAL)</a></h3>
<p>The job of the HAL is to build up on top of
the chip's PAC and provide an abstraction that is actually usable for
someone who does not know about all the special behaviour of this chip.
Usually they abstract whole peripherals away into single structs that can
for example be used to send data around via the peripheral. We are
going to use the <a href="https://crates.io/crates/nrf52833-hal">nRF52-hal</a> or the <a href="https://crates.io/crates/nrf51-hal">nRF51-hal</a> respectively.</p>
<h3 id="the-board-support-crate-historically-called-board-support-package-or-bsp"><a class="header" href="#the-board-support-crate-historically-called-board-support-package-or-bsp">The Board Support Crate (historically called Board Support Package, or BSP)</a></h3>
<p>The job of the BSP is to abstract a whole board
(such as the micro:bit) away at once. That means it has to provide
abstractions to use both the microcontroller as well as the sensors,
LEDs etc. that might be present on the board. Quite often (especially
with custom-made boards) you will just be working with a HAL for the
chip and build the drivers for the sensors either yourself or
search for them on crates.io. Luckily for us though, the micro:bit
does actually have a <a href="https://crates.io/crates/microbit">BSP</a> so we are going to use that on top of our
HAL as well.</p>
<h2 id="unifying-the-layers"><a class="header" href="#unifying-the-layers">Unifying the layers</a></h2>
<p>Next we are going to have a look at a very central piece of software
in the Rust Embedded world: <a href="https://crates.io/crates/embedded-hal"><code>embedded-hal</code></a>. As its name suggests it
relates to the 2nd level of abstraction we got to know: the HALs.
The idea behind <a href="https://crates.io/crates/embedded-hal"><code>embedded-hal</code></a> is to provide a set of traits that
describe behaviour which is usually shared across all implementations
of a specific peripheral in all the HALs. For example one would always
expect to have functions that are capable of turning the power on a pin
either on or off. For example to switch an LED on and off on the board.
This allows us to write a driver for, say a temperature sensor, that
can be used on any chip for which an implementation of the <a href="https://crates.io/crates/embedded-hal"><code>embedded-hal</code></a> traits exists,
simply by writing the driver in such a way that it only relies on the
<a href="https://crates.io/crates/embedded-hal"><code>embedded-hal</code></a> traits. Drivers that are written in such a way are called
platform agnostic and luckily for us most of the drivers on crates.io
are actually platform agnostic.</p>
<h2 id="further-reading"><a class="header" href="#further-reading">Further reading</a></h2>
<p>If you want to learn more about these levels of abstraction, Franz Skarman,
a.k.a. <a href="https://github.com/TheZoq2/">TheZoq2</a>, held a talk about this topic during Oxidize 2020, called
<a href="https://www.youtube.com/watch?v=vLYit_HHPaY">An Overview of the Embedded Rust Ecosystem</a>.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="led-roulette"><a class="header" href="#led-roulette">LED roulette</a></h1>
<p>Alright, let's start by building the following application:</p>
<p align="center">
<video src="../assets/roulette_fast.mp4" loop autoplay>
</p>
<p>I'm going to give you a high level API to implement this app but don't worry we'll do low level
stuff later on. The main goal of this chapter is to get familiar with the <em>flashing</em> and debugging
process.</p>
<p>The starter code is in the <code>src</code> directory of the book repository. Inside that directory there are more
directories named after each chapter of this book. Most of those directories are starter Cargo
projects.</p>
<p>Now, jump into the <code>src/05-led-roulette</code> directory. Check the <code>src/main.rs</code> file:</p>
<pre><pre class="playground"><code class="language-rust">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use panic_halt as _;
use microbit as _;

#[entry]
fn main() -&gt; ! {
    let _y;
    let x = 42;
    _y = x;

    // infinite loop; just so we don't leave this stack frame
    loop {}
}
</code></pre></pre>
<p>Microcontroller programs are different from standard programs in two aspects: <code>#![no_std]</code> and
<code>#![no_main]</code>.</p>
<p>The <code>no_std</code> attribute says that this program won't use the <code>std</code> crate, which assumes an underlying
OS; the program will instead use the <code>core</code> crate, a subset of <code>std</code> that can run on bare metal
systems (i.e., systems without OS abstractions like files and sockets).</p>
<p>The <code>no_main</code> attribute says that this program won't use the standard <code>main</code> interface, which is
tailored for command line applications that receive arguments. Instead of the standard <code>main</code> we'll
use the <code>entry</code> attribute from the <a href="https://crates.io/crates/cortex-m-rt"><code>cortex-m-rt</code></a> crate to define a custom entry point. In this
program we have named the entry point &quot;main&quot;, but any other name could have been used. The entry
point function must have signature <code>fn() -&gt; !</code>; this type indicates that the function can't return
-- this means that the program never terminates.</p>
<p>If you are a careful observer, you'll also notice there is a <code>.cargo</code> directory in the Cargo project
as well. This directory contains a Cargo configuration file (<code>.cargo/config</code>) that tweaks the
linking process to tailor the memory layout of the program to the requirements of the target device.
This modified linking process is a requirement of the <code>cortex-m-rt</code> crate.</p>
<p>Furthermore, there is also an <code>Embed.toml</code> file</p>
<pre><code class="language-toml">[default.general]
# chip = &quot;nrf52833_xxAA&quot; # uncomment this line for micro:bit V2
# chip = &quot;nrf51822_xxAA&quot; # uncomment this line for micro:bit V1

[default.reset]
halt_afterwards = true

[default.rtt]
enabled = false

[default.gdb]
enabled = true
</code></pre>
<p>This file tells <code>cargo-embed</code> that:</p>
<ul>
<li>we are working with either a nrf52833 or nrf51822, you will again have to remove the comments from the
chip you are using, just like you did in chapter 3.</li>
<li>we want to halt the chip after we flashed it so our program does not instantly jump to the loop</li>
<li>we want to disable RTT, RTT being a protocol that allows the chip to send text to a debugger.
You have in fact already seen RTT in action, it was the protocol that sent &quot;Hello World&quot; in chapter 3.</li>
<li>we want to enable GDB, this will be required for the debugging procedure</li>
</ul>
<p>Alright, let's start by building this program.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="build-it"><a class="header" href="#build-it">Build it</a></h1>
<p>The first step is to build our &quot;binary&quot; crate. Because the microcontroller has a different
architecture than your computer we'll have to cross compile. Cross compiling in Rust land is as simple
as passing an extra <code>--target</code> flag to <code>rustc</code>or Cargo. The complicated part is figuring out the
argument of that flag: the <em>name</em> of the target.</p>
<p>As we already know the microcontroller on the micro:bit v2 has a Cortex-M4F processor in it, the one on v1 a Cortex-M0.
<code>rustc</code> knows how to cross-compile to the Cortex-M architecture and provides several different targets that cover the different processors
families within that architecture:</p>
<ul>
<li><code>thumbv6m-none-eabi</code>, for the Cortex-M0 and Cortex-M1 processors</li>
<li><code>thumbv7m-none-eabi</code>, for the Cortex-M3 processor</li>
<li><code>thumbv7em-none-eabi</code>, for the Cortex-M4 and Cortex-M7 processors</li>
<li><code>thumbv7em-none-eabihf</code>, for the Cortex-M4<strong>F</strong> and Cortex-M7<strong>F</strong> processors</li>
<li><code>thumbv8m.main-none-eabi</code>, for the Cortex-M33 and Cortex-M35P processors</li>
<li><code>thumbv8m.main-none-eabihf</code>, for the Cortex-M33<strong>F</strong> and Cortex-M35P<strong>F</strong> processors</li>
</ul>
<p>For the micro:bit v2, we'll use the <code>thumbv7em-none-eabihf</code> target, for v1 the <code>thumbv6m-none-eabi</code> one.
Before cross-compiling you have to download a pre-compiled version of the standard library
(a reduced version of it, actually) for your target. That's done using <code>rustup</code>:</p>
<pre><code class="language-console"># For micro:bit v2
$ rustup target add thumbv7em-none-eabihf
# For micro:bit v1
$ rustup target add thumbv6m-none-eabi
</code></pre>
<p>You only need to do the above step once; <code>rustup</code> will re-install a new standard library
(<code>rust-std</code> component) whenever you update your toolchain. Therefore you can skip this step, if you have already added the necessary target
while [verifying your setup].</p>
<p>With the <code>rust-std</code> component in place you can now cross compile the program using Cargo:</p>
<pre><code class="language-console"># make sure you are in the `src/05-led-roulette` directory

# For micro:bit v2
$ cargo build --features v2 --target thumbv7em-none-eabihf
   Compiling semver-parser v0.7.0
   Compiling typenum v1.12.0
   Compiling cortex-m v0.6.3
   (...)
   Compiling microbit-v2 v0.10.1
    Finished dev [unoptimized + debuginfo] target(s) in 33.67s

# For micro:bit v1
$ cargo build --features v1 --target thumbv6m-none-eabi
   Compiling fixed v1.2.0
   Compiling syn v1.0.39
   Compiling cortex-m v0.6.3
   (...)
   Compiling microbit v0.10.1
	Finished dev [unoptimized + debuginfo] target(s) in 22.73s
</code></pre>
<blockquote>
<p><strong>NOTE</strong> Be sure to compile this crate <em>without</em> optimizations. The provided Cargo.toml
file and build command above will ensure optimizations are off.</p>
</blockquote>
<p>OK, now we have produced an executable. This executable won't blink any LEDs,
it's just a simplified version that we will build upon later in the chapter.
As a sanity check, let's verify that the produced executable is actually an ARM binary:</p>
<pre><code class="language-console"># For micro:bit v2
# equivalent to `readelf -h target/thumbv7em-none-eabihf/debug/led-roulette`
$ cargo readobj --features v2 --target thumbv7em-none-eabihf --bin led-roulette -- --file-headers
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           ARM
  Version:                           0x1
  Entry point address:               0x117
  Start of program headers:          52 (bytes into file)
  Start of section headers:          793112 (bytes into file)
  Flags:                             0x5000400
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         4
  Size of section headers:           40 (bytes)
  Number of section headers:         21
  Section header string table index: 19

# For micro:bit v1
# equivalent to `readelf -h target/thumbv6m-none-eabi/debug/led-roulette`
$ cargo readobj --features v1 --target thumbv6m-none-eabi --bin led-roulette -- --file-headers
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           ARM
  Version:                           0x1
  Entry point address:               0xC1
  Start of program headers:          52 (bytes into file)
  Start of section headers:          693196 (bytes into file)
  Flags:                             0x5000200
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         4
  Size of section headers:           40 (bytes)
  Number of section headers:         22
  Section header string table index: 20
</code></pre>
<p>Next, we'll flash the program into our microcontroller.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="flash-it"><a class="header" href="#flash-it">Flash it</a></h1>
<p>Flashing is the process of moving our program into the microcontroller's (persistent) memory. Once
flashed, the microcontroller will execute the flashed program every time it is powered on.</p>
<p>In this case, our <code>led-roulette</code> program will be the <em>only</em> program in the microcontroller memory.
By this I mean that there's nothing else running on the microcontroller: no OS, no &quot;daemon&quot;,
nothing. <code>led-roulette</code> has full control over the device.</p>
<p>Flashing the binary itself is quite simple thanks to <code>cargo embed</code>.</p>
<p>Before executing that command though, let's look into what it actually does. If you look at the side of your micro:bit
with the USB connector facing upwards you will notice, that there are actually 2 black squares on there
(on the micro:bit v2 there is a third and biggest one, which is a speaker), one is our MCU
we already talked about but what purpose does the other one serve? The other chip has 3 main purposes:</p>
<ol>
<li>Provide power from the USB connector to our MCU</li>
<li>Provide a serial to USB bridge for our MCU (we will look into that in a later chapter)</li>
<li>Being a programmer/debugger (this is the relevant purpose for now)</li>
</ol>
<p>Basically this chip acts as a bridge between our computer (to which it is connected via USB) and the MCU (to which it is
connected via traces and communicates with using the SWD protocol). This bridge enables us to flash new binaries on to
the MCU, inspect its state via a debugger and other things.</p>
<p>So lets flash it!</p>
<pre><code class="language-console"># For micro:bit v2
$ cargo embed --features v2 --target thumbv7em-none-eabihf
  (...)
     Erasing sectors ✔ [00:00:00] [####################################################################################################################################################]  2.00KiB/ 2.00KiB @  4.21KiB/s (eta 0s )
 Programming pages   ✔ [00:00:00] [####################################################################################################################################################]  2.00KiB/ 2.00KiB @  2.71KiB/s (eta 0s )
    Finished flashing in 0.608s

# For micro:bit v1
$ cargo embed --features v1 --target thumbv6m-none-eabi
  (...)
     Erasing sectors ✔ [00:00:00] [####################################################################################################################################################]  2.00KiB/ 2.00KiB @  4.14KiB/s (eta 0s )
 Programming pages   ✔ [00:00:00] [####################################################################################################################################################]  2.00KiB/ 2.00KiB @  2.69KiB/s (eta 0s )
    Finished flashing in 0.614s
</code></pre>
<p>You will notice that <code>cargo-embed</code> blocks after outputting the last line, this is intended and you should not close it
since we need it in this state for the next step: debugging it! Furthermore, you will have noticed that the <code>cargo build</code>
and <code>cargo embed</code> are actually passed the same flags, this is because <code>cargo embed</code> actually executes the build and then
flashes the resulting binary on to the chip, hence you can leave out the <code>cargo build</code> step in the future if you
want to flash your code right away.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="debug-it"><a class="header" href="#debug-it">Debug it</a></h1>
<h2 id="how-does-this-even-work"><a class="header" href="#how-does-this-even-work">How does this even work?</a></h2>
<p>Before we debug our little program let's take a moment to quickly understand what is actually
happening here. In the previous chapter we already discussed the purpose of the second chip
on the board as well as how it talks to our computer, but how can we actually use it?</p>
<p>The little option <code>default.gdb.enabled = true</code> in <code>Embed.toml</code> made <code>cargo-embed</code> open a so-called &quot;GDB stub&quot; after flashing,
this is a server that our GDB can connect to and send commands like &quot;set a breakpoint at address X&quot; to. The server can then decide
on its own how to handle this command. In the case of the <code>cargo-embed</code> GDB stub it will forward the
command to the debugging probe on the board via USB which then does the job of actually talking to the
MCU for us.</p>
<h2 id="lets-debug"><a class="header" href="#lets-debug">Let's debug!</a></h2>
<p>Since <code>cargo-embed</code> is blocking our current shell we can simply open a new one and cd back into our project
directory. Once we are there we first have to open the binary in gdb like this:</p>
<pre><code class="language-shell"># For micro:bit v2
$ gdb target/thumbv7em-none-eabihf/debug/led-roulette

# For micro:bit v1
$ gdb target/thumbv6m-none-eabi/debug/led-roulette
</code></pre>
<blockquote>
<p><strong>NOTE</strong> Depending on which GDB you installed you will have to use a different command to launch it,
check out <a href="05-led-roulette/../03-setup/index.html#tools">chapter 3</a> if you forgot which one it was.</p>
</blockquote>
<blockquote>
<p><strong>NOTE</strong>: If <code>cargo-embed</code> prints a lot of warnings here don't worry about it. As of now it does not fully
implement the GDB protocol and thus might not recognize all the commands your GDB is sending to it,
as long as it does not crash, you are fine.</p>
</blockquote>
<p>Next we will have to connect to the GDB stub. It runs on <code>localhost:1337</code> per default so in order to
connect to it run the following:</p>
<pre><code class="language-shell">(gdb) target remote :1337
Remote debugging using :1337
0x00000116 in nrf52833_pac::{{impl}}::fmt (self=0xd472e165, f=0x3c195ff7) at /home/nix/.cargo/registry/src/github.com-1ecc6299db9ec823/nrf52833-pac-0.9.0/src/lib.rs:157
157     #[derive(Copy, Clone, Debug)]
</code></pre>
<p>Next what we want to do is get to the main function of our program.
We will do this by first setting a breakpoint there and the continuing
program execution until we hit the breakpoint:</p>
<pre><code>(gdb) break main
Breakpoint 1 at 0x104: file src/05-led-roulette/src/main.rs, line 9.
Note: automatically using hardware breakpoints for read-only addresses.
(gdb) continue
Continuing.

Breakpoint 1, led_roulette::__cortex_m_rt_main_trampoline () at src/05-led-roulette/src/main.rs:9
9       #[entry]
</code></pre>
<p>Breakpoints can be used to stop the normal flow of a program. The <code>continue</code> command will let the
program run freely <em>until</em> it reaches a breakpoint. In this case, until it reaches the <code>main</code>
function because there's a breakpoint there.</p>
<p>Note that GDB output says &quot;Breakpoint 1&quot;. Remember that our processor can only use a limited amount of these
breakpoints, so it's a good idea to pay attention to these messages. If you happen to run out of breakpoints,
you can list all the current ones with <code>info break</code> and delete desired ones with <code>delete &lt;breakpoint-num&gt;</code>.</p>
<p>For a nicer debugging experience, we'll be using GDB's Text User Interface (TUI). To enter into that
mode, on the GDB shell enter the following command:</p>
<pre><code>(gdb) layout src
</code></pre>
<blockquote>
<p><strong>NOTE</strong> Apologies Windows users. The GDB shipped with the GNU ARM Embedded Toolchain doesn't
support this TUI mode <code>:-(</code>.</p>
</blockquote>
<p><img src="05-led-roulette/../assets/gdb-layout-src.png" alt="GDB session" title="GDB TUI" /></p>
<p>GDB's break command does not only work for function names, it can also break at certain line numbers.
If we wanted to break in line 13 we can simply do:</p>
<pre><code>(gdb) break 13
Breakpoint 2 at 0x110: file src/05-led-roulette/src/main.rs, line 13.
(gdb) continue
Continuing.

Breakpoint 2, led_roulette::__cortex_m_rt_main () at src/05-led-roulette/src/main.rs:13
(gdb)
</code></pre>
<p>At any point you can leave the TUI mode using the following command:</p>
<pre><code>(gdb) tui disable
</code></pre>
<p>We are now &quot;on&quot; the <code>_y = x</code> statement; that statement hasn't been executed yet. This means that <code>x</code>
is initialized but <code>_y</code> is not. Let's inspect those stack/local variables using the <code>print</code> command:</p>
<pre><code>(gdb) print x
$1 = 42
(gdb) print &amp;x
$2 = (*mut i32) 0x20003fe8
(gdb)
</code></pre>
<p>As expected, <code>x</code> contains the value <code>42</code>. The command <code>print &amp;x</code> prints the address of the variable <code>x</code>.
The interesting bit here is that GDB output shows the type of the reference: <code>i32*</code>, a pointer to an <code>i32</code> value.</p>
<p>If we want to continue the program execution line by line we can do that using the <code>next</code> command
so let's proceed to the <code>loop {}</code> statement:</p>
<pre><code>(gdb) next
16          loop {}
</code></pre>
<p>And <code>_y</code> should now be initialized.</p>
<pre><code>(gdb) print _y
$5 = 42
</code></pre>
<p>Instead of printing the local variables one by one, you can also use the <code>info locals</code> command:</p>
<pre><code>(gdb) info locals
x = 42
_y = 42
(gdb)
</code></pre>
<p>If we use <code>next</code> again on top of the <code>loop {}</code> statement, we'll get stuck because the program will
never pass that statement. Instead, we'll switch to the disassemble view with the <code>layout asm</code>
command and advance one instruction at a time using <code>stepi</code>. You can always switch back into Rust
source code view later by issuing the <code>layout src</code> command again.</p>
<blockquote>
<p><strong>NOTE</strong>: If you used the <code>next</code> or <code>continue</code> command by mistake and GDB got stuck, you can get unstuck by hitting <code>Ctrl+C</code>.</p>
</blockquote>
<pre><code>(gdb) layout asm
</code></pre>
<p><img src="05-led-roulette/../assets/gdb-layout-asm.png" alt="GDB session" title="GDB disassemble" /></p>
<p>If you are not using the TUI mode, you can use the <code>disassemble /m</code> command to disassemble the
program around the line you are currently at.</p>
<pre><code>(gdb) disassemble /m
Dump of assembler code for function _ZN12led_roulette18__cortex_m_rt_main17h3e25e3afbec4e196E:
10      fn main() -&gt; ! {
   0x0000010a &lt;+0&gt;:     sub     sp, #8
   0x0000010c &lt;+2&gt;:     movs    r0, #42 ; 0x2a

11          let _y;
12          let x = 42;
   0x0000010e &lt;+4&gt;:     str     r0, [sp, #0]

13          _y = x;
   0x00000110 &lt;+6&gt;:     str     r0, [sp, #4]

14
15          // infinite loop; just so we don't leave this stack frame
16          loop {}
=&gt; 0x00000112 &lt;+8&gt;:     b.n     0x114 &lt;_ZN12led_roulette18__cortex_m_rt_main17h3e25e3afbec4e196E+10&gt;
   0x00000114 &lt;+10&gt;:    b.n     0x114 &lt;_ZN12led_roulette18__cortex_m_rt_main17h3e25e3afbec4e196E+10&gt;

End of assembler dump.
</code></pre>
<p>See the fat arrow <code>=&gt;</code> on the left side? It shows the instruction the processor will execute next.</p>
<p>If not inside the TUI mode on each <code>stepi</code> command GDB will print the statement and the line number
of the instruction the processor will execute next.</p>
<pre><code>(gdb) stepi
16          loop {}
(gdb) stepi
16          loop {}
</code></pre>
<p>One last trick before we move to something more interesting. Enter the following commands into GDB:</p>
<pre><code>(gdb) monitor reset
(gdb) c
Continuing.

Breakpoint 1, led_roulette::__cortex_m_rt_main_trampoline () at src/05-led-roulette/src/main.rs:9
9       #[entry]
(gdb)
</code></pre>
<p>We are now back at the beginning of <code>main</code>!</p>
<p><code>monitor reset</code> will reset the microcontroller and stop it right at the program entry point.
The following <code>continue</code> command will let the program run freely until it reaches the <code>main</code>
function that has a breakpoint on it.</p>
<p>This combo is handy when you, by mistake, skipped over a part of the program that you were
interested in inspecting. You can easily roll back the state of your program back to its very
beginning.</p>
<blockquote>
<p><strong>The fine print</strong>: This <code>reset</code> command doesn't clear or touch RAM. That memory will retain its
values from the previous run. That shouldn't be a problem though, unless your program behavior
depends on the value of <em>uninitialized</em> variables but that's the definition of Undefined Behavior
(UB).</p>
</blockquote>
<p>We are done with this debug session. You can end it with the <code>quit</code> command.</p>
<pre><code>(gdb) quit
A debugging session is active.

        Inferior 1 [Remote target] will be detached.

Quit anyway? (y or n) y
Detaching from program: $PWD/target/thumbv7em-none-eabihf/debug/led-roulette, Remote target
Ending remote debugging.
[Inferior 1 (Remote target) detached]
</code></pre>
<blockquote>
<p><strong>NOTE</strong> If the default GDB CLI is not to your liking check out <a href="https://github.com/cyrus-and/gdb-dashboard#gdb-dashboard">gdb-dashboard</a>. It uses Python to
turn the default GDB CLI into a dashboard that shows registers, the source view, the assembly view
and other things.</p>
</blockquote>
<p>If you want to learn more about what GDB can do, check out the section <a href="05-led-roulette/../appendix/2-how-to-use-gdb/">How to use GDB</a>.</p>
<p>What's next? The high level API I promised.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="light-it-up"><a class="header" href="#light-it-up">Light it up</a></h1>
<h2 id="embedded-hal"><a class="header" href="#embedded-hal">embedded-hal</a></h2>
<p>In this chapter we are going to make one of the many LEDs on the back of the micro:bit light up since this is
basically the &quot;Hello World&quot; of embedded programming. In order to get this task done we will use one of the traits
provided by <code>embedded-hal</code>, specifically the <a href="https://docs.rs/embedded-hal/0.2.6/embedded_hal/digital/v2/trait.OutputPin.html"><code>OutputPin</code></a> trait which allows us to turn a pin on or off.</p>
<h2 id="the-microbit-leds"><a class="header" href="#the-microbit-leds">The micro:bit LEDs</a></h2>
<p>On the back of the micro:bit you can see a 5x5 square of LEDs, usually called an LED matrix. This matrix alignment is
used so that instead of having to use 25 separate pins to drive every single one of the LEDs, we can just use 10 (5+5) pins in
order to control which column and which row of our matrix lights up.</p>
<blockquote>
<p><strong>NOTE</strong> that the micro:bit v1 team implemented this a little differently. Their <a href="https://tech.microbit.org/hardware/schematic/">schematic page</a> says
that it is actually implemented as a 3x9 matrix but a few columns simply remain unused.</p>
</blockquote>
<p>Usually in order to determine which specific pins we have to control in
order to light a specific LED up we would now have to read the
<a href="https://github.com/microbit-foundation/microbit-v2-hardware/blob/main/V2/MicroBit_V2.0.0_S_schematic.PDF">micro:bit v2 schematic</a> or the <a href="https://github.com/bbcmicrobit/hardware/blob/master/V1.5/SCH_BBC-Microbit_V1.5.PDF">micro:bit v1 schematic</a> respectively.
Luckily for us though we can use the aforementioned micro:bit BSP
which abstracts all of this nicely away from us.</p>
<h2 id="actually-lighting-it-up"><a class="header" href="#actually-lighting-it-up">Actually lighting it up!</a></h2>
<p>The code required to light up an LED in the matrix is actually quite simple but it requires a bit of setup. First take
a look at it and then we can go through it step by step:</p>
<pre><pre class="playground"><code class="language-rust">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use panic_halt as _;
use microbit::board::Board;
use microbit::hal::prelude::*;

#[entry]
fn main() -&gt; ! {
    let mut board = Board::take().unwrap();

    board.display_pins.col1.set_low().unwrap();
    board.display_pins.row1.set_high().unwrap();

    loop {}
}
</code></pre></pre>
<p>The first few lines until the main function just do some basic imports and setup we already looked at before.
However, the main function looks pretty different to what we have seen up to now.</p>
<p>The first line is related to how most HALs written in Rust work internally.
As discussed before they are built on top of PAC crates which own (in the Rust sense)
all the peripherals of a chip. <code>let mut board = Board::take().unwrap();</code> basically takes all
these peripherals from the PAC and binds them to a variable. In this specific case we are
not only working with a HAL but with an entire BSP, so this also takes ownership
of the Rust representation of the other chips on the board.</p>
<blockquote>
<p><strong>NOTE</strong>: If you are wondering why we have to call <code>unwrap()</code> here, in theory it is possible for <code>take()</code> to be called
more than once. This would lead to the peripherals being represented by two separate variables and thus lots of
possible confusing behaviour because two variables modify the same resource. In order to avoid this, PACs are
implemented in a way that it would panic if you tried to take the peripherals twice.</p>
</blockquote>
<p>Now we can light the LED connected to <code>row1</code>, <code>col1</code> up by setting the <code>row1</code> pin to high (i.e. switching it on).
The reason we can leave <code>col1</code> set to low is because of how the LED matrix circuit works. Furthermore, <code>embedded-hal</code> is
designed in a way that every operation on hardware can possibly return an error, even just toggling a pin on or off. Since
that is highly unlikely in our case, we can just <code>unwrap()</code> the result.</p>
<h2 id="testing-it"><a class="header" href="#testing-it">Testing it</a></h2>
<p>Testing our little program is quite simple. First put it into <code>src/mains.rs</code>. Afterwards we simply have to run the
<code>cargo embed</code> command from the last section again, let it flash and just like before. Then open our GDB and connect
to the GDB stub:</p>
<pre><code>$ # Your GDB debug command from the last section
(gdb) target remote :1337
Remote debugging using :1337
cortex_m_rt::Reset () at /home/nix/.cargo/registry/src/github.com-1ecc6299db9ec823/cortex-m-rt-0.6.12/src/lib.rs:489
489     pub unsafe extern &quot;C&quot; fn Reset() -&gt; ! {
(gdb)
</code></pre>
<p>If we now let the program run via the GDB <code>continue</code> command, one of the LEDs on the back of the micro:bit should light
up.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="it-blinks"><a class="header" href="#it-blinks">It blinks</a></h1>
<h2 id="delaying"><a class="header" href="#delaying">Delaying</a></h2>
<p>Now we're going to take a brief look into delay abstractions provided by <code>embedded-hal</code>
before combining this with the GPIO abstractions from the previous chapter in order to
finally make an LED blink.</p>
<p><code>embedded-hal</code> provides us with two abstractions to delay the execution of our program:
<a href="https://docs.rs/embedded-hal/0.2.6/embedded_hal/blocking/delay/trait.DelayUs.html"><code>DelayUs</code></a> and <a href="https://docs.rs/embedded-hal/0.2.6/embedded_hal/blocking/delay/trait.DelayMs.html"><code>DelayMs</code></a>. Both of them essentially work the exact same way except
that they accept different units for their delay function.</p>
<p>Inside our MCU, several so-called &quot;timers&quot; exist. They can do various things regarding time for us,
including simply pausing the execution of our program for a fixed amount of time. A very
simple delay-based program that prints something every second might for example look like this:</p>
<pre><code class="language-rs">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use rtt_target::{rtt_init_print, rprintln};
use panic_rtt_target as _;
use microbit::board::Board;
use microbit::hal::timer::Timer;
use microbit::hal::prelude::*;

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let mut board = Board::take().unwrap();

    let mut timer = Timer::new(board.TIMER0);

    loop {
        timer.delay_ms(1000u16);
        rprintln!(&quot;1000 ms passed&quot;);
    }
}
</code></pre>
<p>Note that we changed our panic implementation from <code>panic_halt</code> to
<code>panic_rtt_target</code> here. This will require you to uncomment the two
RTT lines from <code>Cargo.toml</code> and comment the <code>panic-halt</code> one out,
since Rust only allows one panic implementation at a time.</p>
<p>In order to actually see the prints we have to change <code>Embed.toml</code> like this:</p>
<pre><code>[default.general]
# chip = &quot;nrf52833_xxAA&quot; # uncomment this line for micro:bit V2
# chip = &quot;nrf51822_xxAA&quot; # uncomment this line for micro:bit V1

[default.reset]
halt_afterwards = false

[default.rtt]
enabled = true

[default.gdb]
enabled = false
</code></pre>
<p>And now after putting the code into <code>src/main.rs</code> and another quick <code>cargo embed</code> (again with the same flags you used before)
you should see &quot;<code>1000 ms passed</code>&quot; being sent to your console every second from your MCU.</p>
<h2 id="blinking"><a class="header" href="#blinking">Blinking</a></h2>
<p>Now we've arrived at the point where we can combine our new knowledge about GPIO and delay abstractions
in order to actually make an LED on the back of the micro:bit blink. The resulting program is really just
a mash-up of the one above and the one that turned an LED on in the last section and looks like this:</p>
<pre><code class="language-rs">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use rtt_target::{rtt_init_print, rprintln};
use panic_rtt_target as _;
use microbit::board::Board;
use microbit::hal::timer::Timer;
use microbit::hal::prelude::*;

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let mut board = Board::take().unwrap();

    let mut timer = Timer::new(board.TIMER0);

    board.display_pins.col1.set_low().unwrap();
    let mut row1 = board.display_pins.row1;

    loop {
        row1.set_low().unwrap();
        rprintln!(&quot;Dark!&quot;);
        timer.delay_ms(1_000_u16);
        row1.set_high().unwrap();
        rprintln!(&quot;Light!&quot;);
        timer.delay_ms(1_000_u16);
    }
}
</code></pre>
<p>And after putting the code into <code>src/main.rs</code> and a final <code>cargo embed</code> (with the proper flags)
you should see the LED we light up before blinking as well as a print, every time the LED changes from off to on and vice versa.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="the-challenge"><a class="header" href="#the-challenge">The challenge</a></h1>
<p>You are now well armed to face a challenge! Your task will be to implement the application I showed
you at the beginning of this chapter.</p>
<p align="center">
<video src="../assets/roulette_fast.mp4" loop autoplay>
</p>
<p>If you can't exactly see what's happening here it is in a much slower version:</p>
<p align="center">
<video src="../assets/roulette_slow.mp4" loop autoplay>
</p>
<p>Since working with the LED pins separately is quite annoying
(especially if you have to use basically all of them like here)
you can use the display API provided by the BSP. It works like this:</p>
<pre><pre class="playground"><code class="language-rust">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use rtt_target::rtt_init_print;
use panic_rtt_target as _;
use microbit::{
    board::Board,
    display::blocking::Display,
    hal::{prelude::*, Timer},
};

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();

    let board = Board::take().unwrap();
    let mut timer = Timer::new(board.TIMER0);
    let mut display = Display::new(board.display_pins);
    let light_it_all = [
        [1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1],
    ];

    loop {
        // Show light_it_all for 1000ms
        display.show(&amp;mut timer, light_it_all, 1000);
        // clear the display again
        display.clear();
        timer.delay_ms(1000_u32);
    }
}
</code></pre></pre>
<p>Equipped with this API your task basically boils down to just having
to calculate the proper image matrix and passing it into the BSP.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="my-solution"><a class="header" href="#my-solution">My solution</a></h1>
<p>What solution did you come up with?</p>
<p>Here's mine, it's probably one of the simplest (but of course not most
beautiful) way to generate the required matrix:</p>
<pre><pre class="playground"><code class="language-rust">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use rtt_target::rtt_init_print;
use panic_rtt_target as _;
use microbit::{
    board::Board,
    display::blocking::Display,
    hal::Timer,
};

const PIXELS: [(usize, usize); 16] = [
    (0,0), (0,1), (0,2), (0,3), (0,4), (1,4), (2,4), (3,4), (4,4),
    (4,3), (4,2), (4,1), (4,0), (3,0), (2,0), (1,0)
];

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();

    let board = Board::take().unwrap();
    let mut timer = Timer::new(board.TIMER0);
    let mut display = Display::new(board.display_pins);
    let mut leds = [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
    ];

    let mut last_led = (0,0);

    loop {
        for current_led in PIXELS.iter() {
            leds[last_led.0][last_led.1] = 0;
            leds[current_led.0][current_led.1] = 1;
            display.show(&amp;mut timer, leds, 30);
            last_led = *current_led;
        }
    }
}
</code></pre></pre>
<p>One more thing! Check that your solution also works when compiled in &quot;release&quot; mode:</p>
<pre><code class="language-console"># For micro:bit v2
$ cargo embed --features v2 --target thumbv7em-none-eabihf --release
  (...)

# For micro:bit v1
$ cargo embed --features v1 --target thumbv6m-none-eabi --release
  (...)
</code></pre>
<p>If you want to debug your &quot;release&quot; mode binary you'll have to use a different GDB command:</p>
<pre><code class="language-console"># For micro:bit v2
$ gdb target/thumbv7em-none-eabihf/release/led-roulette

# For micro:bit v1
$ gdb target/thumbv6m-none-eabi/release/led-roulette
</code></pre>
<p>Binary size is something we should always keep an eye on! How big is your solution? You can check
that using the <code>size</code> command on the release binary:</p>
<pre><code class="language-console"># For micro:bit v2
$ cargo size --features v2 --target thumbv7em-none-eabihf -- -A
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
led-roulette  :
section               size        addr
.vector_table          256         0x0
.text                26984       0x100
.rodata               2732      0x6a68
.data                    0  0x20000000
.bss                  1092  0x20000000
.uninit                  0  0x20000444
.debug_abbrev        33941         0x0
.debug_info         494113         0x0
.debug_aranges       23528         0x0
.debug_ranges       130824         0x0
.debug_str          498781         0x0
.debug_pubnames     143351         0x0
.debug_pubtypes     124464         0x0
.ARM.attributes         58         0x0
.debug_frame         69128         0x0
.debug_line         290580         0x0
.debug_loc            1449         0x0
.comment               109         0x0
Total              1841390


$ cargo size --features v2 --target thumbv7em-none-eabihf --release -- -A
    Finished release [optimized + debuginfo] target(s) in 0.02s
led-roulette  :
section              size        addr
.vector_table         256         0x0
.text                6332       0x100
.rodata               648      0x19bc
.data                   0  0x20000000
.bss                 1076  0x20000000
.uninit                 0  0x20000434
.debug_loc           9036         0x0
.debug_abbrev        2754         0x0
.debug_info         96460         0x0
.debug_aranges       1120         0x0
.debug_ranges       11520         0x0
.debug_str          71325         0x0
.debug_pubnames     32316         0x0
.debug_pubtypes     29294         0x0
.ARM.attributes        58         0x0
.debug_frame         2108         0x0
.debug_line         19303         0x0
.comment              109         0x0
Total              283715

# micro:bit v1
$ cargo size --features v1 --target thumbv6m-none-eabi -- -A
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
led-roulette  :
section               size        addr
.vector_table          168         0x0
.text                28584        0xa8
.rodata               2948      0x7050
.data                    0  0x20000000
.bss                  1092  0x20000000
.uninit                  0  0x20000444
.debug_abbrev        30020         0x0
.debug_info         373392         0x0
.debug_aranges       18344         0x0
.debug_ranges        89656         0x0
.debug_str          375887         0x0
.debug_pubnames     115633         0x0
.debug_pubtypes      86658         0x0
.ARM.attributes         50         0x0
.debug_frame         54144         0x0
.debug_line         237714         0x0
.debug_loc            1499         0x0
.comment               109         0x0
Total              1415898

$ cargo size --features v1 --target thumbv6m-none-eabi --release -- -A
    Finished release [optimized + debuginfo] target(s) in 0.02s
led-roulette  :
section              size        addr
.vector_table         168         0x0
.text                4848        0xa8
.rodata               648      0x1398
.data                   0  0x20000000
.bss                 1076  0x20000000
.uninit                 0  0x20000434
.debug_loc           9705         0x0
.debug_abbrev        3235         0x0
.debug_info         61908         0x0
.debug_aranges       1208         0x0
.debug_ranges        5784         0x0
.debug_str          57358         0x0
.debug_pubnames     22959         0x0
.debug_pubtypes     18891         0x0
.ARM.attributes        50         0x0
.debug_frame         2316         0x0
.debug_line         18444         0x0
.comment               19         0x0
Total              208617

</code></pre>
<blockquote>
<p><strong>NOTE</strong> The Cargo project is already configured to build the release binary using LTO.</p>
</blockquote>
<p>Know how to read this output? The <code>text</code> section contains the program instructions. On the other hand,
the <code>data</code> and <code>bss</code> sections contain variables statically allocated in RAM (<code>static</code> variables).
If you remember back in the specification of the microcontroller on your micro:bit, you should
notice that its flash memory is actually far too small to contain this binary, so how is this possible?
As we can see from the size statistics most of the binary is actually made up of debugging related
sections, those are however not flashed to the microcontroller at any time, after all they aren't
relevant for the execution.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="serial-communication"><a class="header" href="#serial-communication">Serial communication</a></h1>
<a href="https://en.wikipedia.org/wiki/File:Serial_port.jpg">
<p align="center">
<img height="240" title="Standard serial port connector DE-9" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Serial_port.jpg/800px-Serial_port.jpg">
</p>
</a>
<p align="center">
<em>This is what we'll be using. I hope your computer has one!</em>
</p>
<p>Nah, don't worry. This connector, the DE-9, went out of fashion on PCs quite some time ago; it got
replaced by the Universal Serial Bus (USB). We won't be dealing with the DE-9 connector itself but
with the communication protocol that this cable is/was usually used for.</p>
<p>So what's this <a href="https://en.wikipedia.org/wiki/Asynchronous_serial_communication"><em>serial communication</em></a>? It's an <em>asynchronous</em> communication protocol where two
devices exchange data <em>serially</em>, as in one bit at a time, using two data lines (plus a common
ground). The protocol is asynchronous in the sense that neither of the shared lines carries a clock
signal. Instead, both parties must agree on how fast data will be sent along the wire <em>before</em> the
communication occurs. This protocol allows <em>duplex</em> communication as data can be sent from A to B
and from B to A simultaneously.</p>
<p>We'll be using this protocol to exchange data between the microcontroller and your computer. Now you might
be asking yourself why exactly we aren't using RTT for this like we did before. RTT is a protocol that is meant
to be used solely for debugging. You will most definitely not be able to find a device that actually uses RTT
to communicate with some other device in production. However, serial communication is used quite often. For
example some GPS receivers send the positioning information they receive via serial communication.</p>
<p>The next practical question you probably want to ask is: How fast can we send data through this
protocol?</p>
<p>This protocol works with frames. Each frame has one <em>start</em> bit, 5 to 9 bits of payload (data) and 1
to 2 <em>stop bits</em>. The speed of the protocol is known as <em>baud rate</em> and it's quoted in bits per
second (bps). Common baud rates are: 9600, 19200, 38400, 57600 and 115200 bps.</p>
<p>To actually answer the question: With a common configuration of 1 start bit, 8 bits of data, 1
stop bit and a baud rate of 115200 bps one can, in theory, send 11,520 frames per second. Since each
one frame carries a byte of data that results in a data rate of 11.52 KB/s. In practice, the data
rate will probably be lower because of processing times on the slower side of the communication (the
microcontroller).</p>
<p>Today's computers don't support the serial communication protocol. So you can't directly connect
your computer to the microcontroller. Luckily for us though, the debug probe on the micro:bit has a so-called
USB-to-serial converter. This means that the converter will sit between the two and expose a serial interface to
the microcontroller and a USB interface to your computer. The microcontroller will see your computer as
another serial device and your computer will see the microcontroller as a virtual serial device.</p>
<p>Now, let's get familiar with the serial module and the serial communication tools that your OS
offers. Pick a route:</p>
<ul>
<li><a href="06-serial-communication/nix-tooling.html">*nix</a></li>
<li><a href="06-serial-communication/windows-tooling.html">Windows</a></li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="nix-tooling"><a class="header" href="#nix-tooling">*nix tooling</a></h1>
<h2 id="connecting-the-microbit-board"><a class="header" href="#connecting-the-microbit-board">Connecting the micro:bit board</a></h2>
<p>If you connect the micro:bit board to your computer you
should see a new TTY device appear in <code>/dev</code>.</p>
<pre><code class="language-console">$ # Linux
$ dmesg | tail | grep -i tty
[63712.446286] cdc_acm 1-1.7:1.1: ttyACM0: USB ACM device
</code></pre>
<p>This is the USB &lt;-&gt; Serial device. On Linux, it's named <code>tty*</code> (usually
<code>ttyACM*</code> or <code>ttyUSB*</code>).
On Mac OS <code>ls /dev/cu.usbmodem*</code> will show the serial device.</p>
<p>But what exactly is <code>ttyACM0</code>? It's a file of course!
Everything is a file in *nix:</p>
<pre><code>$ ls -l /dev/ttyACM0
crw-rw----. 1 root plugdev 166, 0 Jan 21 11:56 /dev/ttyACM0
</code></pre>
<p>You can send out data by simply writing to this file:</p>
<pre><code class="language-console">$ echo 'Hello, world!' &gt; /dev/ttyACM0
</code></pre>
<p>You should see the orange LED on the micro:bit, right next to the USB port, blink for a moment,
whenever you enter this command.</p>
<h2 id="minicom"><a class="header" href="#minicom">minicom</a></h2>
<p>We'll use the program <code>minicom</code> to interact with the serial device using the keyboard.</p>
<p>We must configure <code>minicom</code> before we use it. There are quite a few ways to do that but we'll use a
<code>.minirc.dfl</code> file in the home directory. Create a file in <code>~/.minirc.dfl</code> with the following
contents:</p>
<pre><code class="language-console">$ cat ~/.minirc.dfl
pu baudrate 115200
pu bits 8
pu parity N
pu stopbits 1
pu rtscts No
pu xonxoff No
</code></pre>
<blockquote>
<p><strong>NOTE</strong> Make sure this file ends in a newline! Otherwise, <code>minicom</code> will fail to read it.</p>
</blockquote>
<p>That file should be straightforward to read (except for the last two lines), but nonetheless let's
go over it line by line:</p>
<ul>
<li><code>pu baudrate 115200</code>. Sets baud rate to 115200 bps.</li>
<li><code>pu bits 8</code>. 8 bits per frame.</li>
<li><code>pu parity N</code>. No parity check.</li>
<li><code>pu stopbits 1</code>. 1 stop bit.</li>
<li><code>pu rtscts No</code>. No hardware control flow.</li>
<li><code>pu xonxoff No</code>. No software control flow.</li>
</ul>
<p>Once that's in place, we can launch <code>minicom</code>.</p>
<pre><code class="language-console">$ # NOTE you may need to use a different device here
$ minicom -D /dev/ttyACM0 -b 115200
</code></pre>
<p>This tells <code>minicom</code> to open the serial device at <code>/dev/ttyACM0</code> and set its
baud rate to 115200. A text-based user interface (TUI) will pop out.</p>
<p align="center">
<img title="minicom" src="06-serial-communication/../assets/minicom.png">
</p>
<p>You can now send data using the keyboard! Go ahead and type something. Note that
the text UI will <em>not</em> echo back what you type. If you pay attention to the yellow LED
on top of the micro:bit though, you will notice that it blinks whenever you type something.</p>
<h2 id="minicom-commands"><a class="header" href="#minicom-commands"><code>minicom</code> commands</a></h2>
<p><code>minicom</code> exposes commands via keyboard shortcuts. On Linux, the shortcuts start with <code>Ctrl+A</code>. On
Mac, the shortcuts start with the <code>Meta</code> key. Some useful commands below:</p>
<ul>
<li><code>Ctrl+A</code> + <code>Z</code>. Minicom Command Summary</li>
<li><code>Ctrl+A</code> + <code>C</code>. Clear the screen</li>
<li><code>Ctrl+A</code> + <code>X</code>. Exit and reset</li>
<li><code>Ctrl+A</code> + <code>Q</code>. Quit with no reset</li>
</ul>
<blockquote>
<p><strong>NOTE</strong> Mac users: In the above commands, replace <code>Ctrl+A</code> with <code>Meta</code>.</p>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h1 id="windows-tooling"><a class="header" href="#windows-tooling">Windows tooling</a></h1>
<p>Start by unplugging your micro:bit.</p>
<p>Before plugging the micro:bit, run the following command on the terminal:</p>
<pre><code class="language-console">$ mode
</code></pre>
<p>It will print a list of devices that are connected to your computer. The ones that start with <code>COM</code> in
their names are serial devices. This is the kind of device we'll be working with. Take note of all
the <code>COM</code> <em>ports</em> <code>mode</code> outputs <em>before</em> plugging the serial module.</p>
<p>Now, plug the micro:bit and run the <code>mode</code> command again. If you see a new
<code>COM</code> port appear on the list then you have that's the COM port assigned to the
serial functionality on the micro:bit.</p>
<p>Now launch <code>putty</code>. A GUI will pop out.</p>
<p align="center">
<img title="PuTTY settings" src="06-serial-communication/../assets/putty-settings.png">
</p>
<p>On the starter screen, which should have the &quot;Session&quot; category open, pick &quot;Serial&quot; as the
&quot;Connection type&quot;. On the &quot;Serial line&quot; field enter the <code>COM</code> device you got on the previous step,
for example <code>COM3</code>.</p>
<p>Next, pick the &quot;Connection/Serial&quot; category from the menu on the left. On this new view, make sure
that the serial port is configured as follows:</p>
<ul>
<li>&quot;Speed (baud)&quot;: 115200</li>
<li>&quot;Data bits&quot;: 8</li>
<li>&quot;Stop bits&quot;: 1</li>
<li>&quot;Parity&quot;: None</li>
<li>&quot;Flow control&quot;: None</li>
</ul>
<p>Finally, click the Open button. A console will show up now:</p>
<p align="center">
<img title="PuTTY console" src="06-serial-communication/../assets/putty-console.png">
</p>
<p>If you type on this console, the yellow LED on top of the micro:bit will blink. Each keystroke
should make the LED blink once. Note that the console won't echo back what you type so the screen
will remain blank.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="uart"><a class="header" href="#uart">UART</a></h1>
<p>The microcontroller has a peripheral called UART, which stands for Universal
Asynchronous Receiver/Transmitter. This peripheral can be configured to work with
several communication protocols like the serial communication protocol.</p>
<p>Throughout this chapter, we'll use serial communication to exchange information between the
microcontroller and your computer.</p>
<blockquote>
<p><strong>NOTE</strong> that on the micro:bit v2 we will use the so called UARTE peripheral which behaves
just like a regular UART, except that the HAL has to talk to it differently.
However, this will of course not be our concern.</p>
</blockquote>
<h2 id="setup"><a class="header" href="#setup">Setup</a></h2>
<p>As always from now on you will have to modify the <code>Embed.toml</code> to match your micro:bit version:</p>
<pre><code class="language-toml">[default.general]
# chip = &quot;nrf52833_xxAA&quot; # uncomment this line for micro:bit V2
# chip = &quot;nrf51822_xxAA&quot; # uncomment this line for micro:bit V1

[default.reset]
halt_afterwards = false

[default.rtt]
enabled = true

[default.gdb]
enabled = false
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="send-a-single-byte"><a class="header" href="#send-a-single-byte">Send a single byte</a></h1>
<p>Our first task will be to send a single byte from the microcontroller to the computer over the serial
connection.</p>
<p>In order to do that we will use the following snippet (this one is already in <code>07-uart/src/main.rs</code>):</p>
<pre><pre class="playground"><code class="language-rust">#![no_main]
#![no_std]

use cortex_m_rt::entry;
use rtt_target::rtt_init_print;
use panic_rtt_target as _;

#[cfg(feature = &quot;v1&quot;)]
use microbit::{
    hal::prelude::*,
    hal::uart,
    hal::uart::{Baudrate, Parity},
};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{
    hal::prelude::*,
    hal::uarte,
    hal::uarte::{Baudrate, Parity},
};

#[cfg(feature = &quot;v2&quot;)]
mod serial_setup;
#[cfg(feature = &quot;v2&quot;)]
use serial_setup::UartePort;

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();

    #[cfg(feature = &quot;v1&quot;)]
    let mut serial = {
        uart::Uart::new(
            board.UART0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        )
    };

    #[cfg(feature = &quot;v2&quot;)]
    let mut serial = {
        let serial = uarte::Uarte::new(
            board.UARTE0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        );
        UartePort::new(serial)
    };

    nb::block!(serial.write(b'X')).unwrap();
    nb::block!(serial.flush()).unwrap();

    loop {}
}
</code></pre></pre>
<p>The most prevalent new thing here is obviously the <code>cfg</code> directives to conditionally include/exclude
parts of the code. This is mostly just because we want to work with a regular UART for the micro:bit v1
and with the UARTE for micro:bit v2.</p>
<p>You will also have noticed that this is the first time we are including some code that is not from a library,
namely the <code>serial_setup</code> module. Its only purpose is to provide a nice wrapper around the UARTE
so we can use it the exact same way as the UART via the <a href="https://docs.rs/embedded-hal/0.2.6/embedded_hal/serial/index.html"><code>embedded_hal::serial</code></a> traits. If you want, you can
check out what exactly the module does, but it is not required to understand this chapter in general.</p>
<p>Apart from those differences, the initialization procedures for the UART and the UARTE are quite similar so we'll
discuss the initialization of just UARTE. The UARTE is initialized with this piece of code:</p>
<pre><code class="language-rs">uarte::Uarte::new(
    board.UARTE0,
    board.uart.into(),
    Parity::EXCLUDED,
    Baudrate::BAUD115200,
);
</code></pre>
<p>This function takes ownership of the UARTE peripheral representation in Rust (<code>board.UARTE0</code>) and the TX/RX pins
on the board (<code>board.uart.into()</code>) so nobody else can mess with either the UARTE peripheral or our pins while
we are using them. After that we pass two configuration options to the constructor: the baudrate (that one should be
familiar) as well as an option called &quot;parity&quot;. Parity is a way to allow serial communication lines to check whether
the data they received was corrupted during transmission. We don't want to use that here so we simply exclude it.
Then we wrap it up in the <code>UartePort</code> type so we can use it the same way as the micro:bit v1's <code>serial</code>.</p>
<p>After the initialization, we send our <code>X</code> via the newly created uart instance. The <code>block!</code> macro here is the <code>nb::block!</code>
macro. <code>nb</code> is a (quoting from its description) &quot;Minimal and reusable non-blocking I/O layer&quot;. It allows us to write
code that can conduct hardware operations in the background while we go and do other work (non-blocking). However,
in this and many other cases we have no interest in doing some other work so we just call <code>block!</code> which will wait until
the I/O operation is done and has either succeeded or failed and then continue execution normally.</p>
<p>Last but not least, we <code>flush()</code> the serial port. This is because an implementor of the <code>embedded-hal::serial</code> traits may
decide to buffer output until it has received a certain number of bytes to send (this is the case with the UARTE implementation).
Calling <code>flush()</code> forces it to write the bytes it currently has right now instead of waiting for more.</p>
<h2 id="testing-it-1"><a class="header" href="#testing-it-1">Testing it</a></h2>
<p>Before flashing this you should make sure to start your minicom/PuTTY as the data we receive via our serial
communication is not backed up or anything, we have to view it live. Once your serial monitor is up you can
flash the program just like in chapter 5:</p>
<pre><code># For micro:bit v2
$ cargo embed --features v2 --target thumbv7em-none-eabihf
  (...)

# For micro:bit v1
$ cargo embed --features v1 --target thumbv6m-none-eabi
</code></pre>
<p>And after the flashing is finished, you should see the character <code>X</code> show up on your minicom/PuTTY terminal, congrats!</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="send-a-string"><a class="header" href="#send-a-string">Send a string</a></h1>
<p>The next task will be to send a whole string from the microcontroller to your computer.</p>
<p>I want you to send the string <code>&quot;The quick brown fox jumps over the lazy dog.&quot;</code> from the microcontroller to
your computer.</p>
<p>It's your turn to write the program.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="naive-approach-and-write"><a class="header" href="#naive-approach-and-write">Naive approach and <code>write!</code></a></h1>
<h2 id="naive-approach"><a class="header" href="#naive-approach">Naive approach</a></h2>
<p>You probably came up with a program similar to the following:</p>
<pre><code class="language-rs">#![no_main]
#![no_std]

use cortex_m_rt::entry;
use rtt_target::rtt_init_print;
use panic_rtt_target as _;

#[cfg(feature = &quot;v1&quot;)]
use microbit::{
    hal::prelude::*,
    hal::uart,
    hal::uart::{Baudrate, Parity},
};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{
    hal::prelude::*,
    hal::uarte,
    hal::uarte::{Baudrate, Parity},
};

#[cfg(feature = &quot;v2&quot;)]
mod serial_setup;
#[cfg(feature = &quot;v2&quot;)]
use serial_setup::UartePort;

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();

    #[cfg(feature = &quot;v1&quot;)]
    let mut serial = {
        uart::Uart::new(
            board.UART0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        )
    };

    #[cfg(feature = &quot;v2&quot;)]
    let mut serial = {
        let serial = uarte::Uarte::new(
            board.UARTE0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        );
        UartePort::new(serial)
    };

    for byte in b&quot;The quick brown fox jumps over the lazy dog.\r\n&quot;.iter() {
        nb::block!(serial.write(*byte)).unwrap();
    }
    nb::block!(serial.flush()).unwrap();

    loop {}
}
</code></pre>
<p>While this is a perfectly valid implementation, at some point
you might want to have all the nice perks of <code>print!</code> such
as argument formatting and so on. If you are wondering how to do that, read on.</p>
<h2 id="write-and-corefmtwrite"><a class="header" href="#write-and-corefmtwrite"><code>write!</code> and <code>core::fmt::Write</code></a></h2>
<p>The <code>core::fmt::Write</code> trait allows us to use any struct that implements
it in basically the same way as we use <code>print!</code> in the <code>std</code> world.
In this case, the <code>Uart</code> struct from the <code>nrf</code> HAL does implement <code>core::fmt::Write</code>
so we can refactor our previous program into this:</p>
<pre><code class="language-rs">#![no_main]
#![no_std]

use cortex_m_rt::entry;
use rtt_target::rtt_init_print;
use panic_rtt_target as _;
use core::fmt::Write;

#[cfg(feature = &quot;v1&quot;)]
use microbit::{
    hal::prelude::*,
    hal::uart,
    hal::uart::{Baudrate, Parity},
};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{
    hal::prelude::*,
    hal::uarte,
    hal::uarte::{Baudrate, Parity},
};

#[cfg(feature = &quot;v2&quot;)]
mod serial_setup;
#[cfg(feature = &quot;v2&quot;)]
use serial_setup::UartePort;

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();

    #[cfg(feature = &quot;v1&quot;)]
    let mut serial = {
        uart::Uart::new(
            board.UART0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        )
    };

    #[cfg(feature = &quot;v2&quot;)]
    let mut serial = {
        let serial = uarte::Uarte::new(
            board.UARTE0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        );
        UartePort::new(serial)
    };

    write!(serial, &quot;The quick brown fox jumps over the lazy dog.\r\n&quot;).unwrap();
    nb::block!(serial.flush()).unwrap();

    loop {}
}
</code></pre>
<p>If you were to flash this program onto your micro:bit, you'll
see that it is functionally equivalent to the iterator-based
program you came up with.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="receive-a-single-byte"><a class="header" href="#receive-a-single-byte">Receive a single byte</a></h1>
<p>So far we can send data from the microcontroller to your computer. It's time to try the opposite: receiving
data from your computer. Luckily <code>embedded-hal</code> has again got us covered with this one:</p>
<pre><pre class="playground"><code class="language-rust">#![no_main]
#![no_std]

use cortex_m_rt::entry;
use rtt_target::{rtt_init_print, rprintln};
use panic_rtt_target as _;

#[cfg(feature = &quot;v1&quot;)]
use microbit::{
    hal::prelude::*,
    hal::uart,
    hal::uart::{Baudrate, Parity},
};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{
    hal::prelude::*,
    hal::uarte,
    hal::uarte::{Baudrate, Parity},
};

#[cfg(feature = &quot;v2&quot;)]
mod serial_setup;
#[cfg(feature = &quot;v2&quot;)]
use serial_setup::UartePort;

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();

    #[cfg(feature = &quot;v1&quot;)]
    let mut serial = {
        uart::Uart::new(
            board.UART0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        )
    };

    #[cfg(feature = &quot;v2&quot;)]
    let mut serial = {
        let serial = uarte::Uarte::new(
            board.UARTE0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        );
        UartePort::new(serial)
    };

    loop {
        let byte = nb::block!(serial.read()).unwrap();
        rprintln!(&quot;{}&quot;, byte);
    }
}
</code></pre></pre>
<p>The only part that changed, compared to our send byte program, is the loop
at the end of <code>main()</code>. Here we use the <code>read()</code> function, provided by <code>embedded-hal</code>,
in order to wait until a byte is available and read it. Then we print that byte
into our RTT debugging console to see whether stuff is actually arriving.</p>
<p>Note that if you flash this program and start typing characters inside <code>minicom</code> to
send them to your microcontroller you'll only be able to see numbers inside your
RTT console since we are not converting the <code>u8</code> we received into an actual <code>char</code>.
Since the conversion from <code>u8</code> to <code>char</code> is quite simple, I'll leave this task to
you if you really do want to see the characters inside the RTT console.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="echo-server"><a class="header" href="#echo-server">Echo server</a></h1>
<p>Let's merge transmission and reception into a single program and write an echo server. An echo
server sends back to the client the same text it receives. For this application, the microcontroller
will be the server and you and your computer will be the client.</p>
<p>This should be straightforward to implement. (hint: do it byte by byte)</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="reverse-a-string"><a class="header" href="#reverse-a-string">Reverse a string</a></h1>
<p>Alright, next let's make the server more interesting by having it respond to the client with the
reverse of the text that they sent. The server will respond to the client every time they press the
ENTER key. Each server response will be in a new line.</p>
<p>This time you'll need a buffer; you can use <a href="https://docs.rs/heapless/latest/heapless/struct.Vec.html"><code>heapless::Vec</code></a>. Here's the starter code:</p>
<pre><pre class="playground"><code class="language-rust">#![no_main]
#![no_std]

use cortex_m_rt::entry;
use core::fmt::Write;
use heapless::Vec;
use rtt_target::rtt_init_print;
use panic_rtt_target as _;

#[cfg(feature = &quot;v1&quot;)]
use microbit::{
    hal::prelude::*,
    hal::uart,
    hal::uart::{Baudrate, Parity},
};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{
    hal::prelude::*,
    hal::uarte,
    hal::uarte::{Baudrate, Parity},
};

#[cfg(feature = &quot;v2&quot;)]
mod serial_setup;
#[cfg(feature = &quot;v2&quot;)]
use serial_setup::UartePort;

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();

    #[cfg(feature = &quot;v1&quot;)]
    let mut serial = {
        uart::Uart::new(
            board.UART0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        )
    };

    #[cfg(feature = &quot;v2&quot;)]
    let mut serial = {
        let serial = uarte::Uarte::new(
            board.UARTE0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        );
        UartePort::new(serial)
    };

    // A buffer with 32 bytes of capacity
    let mut buffer: Vec&lt;u8, 32&gt; = Vec::new();

    loop {
        buffer.clear();

        // TODO Receive a user request. Each user request ends with ENTER
        // NOTE `buffer.push` returns a `Result`. Handle the error by responding
        // with an error message.

        // TODO Send back the reversed string
    }
}
</code></pre></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="my-solution-1"><a class="header" href="#my-solution-1">My solution</a></h1>
<pre><pre class="playground"><code class="language-rust">#![no_main]
#![no_std]

use cortex_m_rt::entry;
use core::fmt::Write;
use heapless::Vec;
use rtt_target::rtt_init_print;
use panic_rtt_target as _;

#[cfg(feature = &quot;v1&quot;)]
use microbit::{
    hal::prelude::*,
    hal::uart,
    hal::uart::{Baudrate, Parity},
};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{
    hal::prelude::*,
    hal::uarte,
    hal::uarte::{Baudrate, Parity},
};

#[cfg(feature = &quot;v2&quot;)]
mod serial_setup;
#[cfg(feature = &quot;v2&quot;)]
use serial_setup::UartePort;

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();

    #[cfg(feature = &quot;v1&quot;)]
    let mut serial = {
        uart::Uart::new(
            board.UART0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        )
    };

    #[cfg(feature = &quot;v2&quot;)]
    let mut serial = {
        let serial = uarte::Uarte::new(
            board.UARTE0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        );
        UartePort::new(serial)
    };

    // A buffer with 32 bytes of capacity
    let mut buffer: Vec&lt;u8, 32&gt; = Vec::new();

    loop {
        buffer.clear();

        loop {
            // We assume that the receiving cannot fail
            let byte = nb::block!(serial.read()).unwrap();

            if buffer.push(byte).is_err() {
                write!(serial, &quot;error: buffer full\r\n&quot;).unwrap();
                break;
            }

            if byte == 13 {
                for byte in buffer.iter().rev().chain(&amp;[b'\n', b'\r']) {
                    nb::block!(serial.write(*byte)).unwrap();
                }
                break;
            }
        }
        nb::block!(serial.flush()).unwrap()
    }
}
</code></pre></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="i2c"><a class="header" href="#i2c">I2C</a></h1>
<p>We just saw the serial communication protocol. It's a widely used protocol because it's very
simple and this simplicity makes it easy to implement on top of other protocols like Bluetooth and
USB.</p>
<p>However, its simplicity is also a downside. More elaborated data exchanges, like reading a digital
sensor, would require the sensor vendor to come up with another protocol on top of it.</p>
<p>(Un)Luckily for us, there are <em>plenty</em> of other communication protocols in the embedded space. Some
of them are widely used in digital sensors.</p>
<p>The micro:bit board we are using has two motion sensors in it: an accelerometer and a magnetometer.
Both of these sensors are packaged into a single component and can be accessed via an I2C bus.</p>
<p>I2C stands for Inter-Integrated Circuit and is a <em>synchronous</em> <em>serial</em> communication protocol. It
uses two lines to exchange data: a data line (SDA) and a clock line (SCL). Because a clock line is
used to synchronize the communication, this is a <em>synchronous</em> protocol.</p>
<p align="center">
<img class="white_bg" height=180 title="I2C bus" src="https://upload.wikimedia.org/wikipedia/commons/3/3e/I2C.svg">
</p>
<p>This protocol uses a <em>master</em> <em>slave</em> model where the master is the device that <em>starts</em> and
drives the communication with a slave device. Several devices, both masters and slaves, can be
connected to the same bus at the same time. A master device can communicate with a specific slave
device by first broadcasting its <em>address</em> to the bus. This address can be 7 bits or 10 bits long.
Once a master has <em>started</em> a communication with a slave, no other device can make use of the bus
until the master <em>stops</em> the communication.</p>
<p>The clock line determines how fast data can be exchanged and it usually operates at a frequency of
100 kHz (standard mode) or 400 kHz (fast mode).</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="general-protocol"><a class="header" href="#general-protocol">General protocol</a></h1>
<p>The I2C protocol is more elaborate than the serial communication protocol because it has to support
communication between several devices. Let's see how it works using examples:</p>
<h2 id="master---slave"><a class="header" href="#master---slave">Master -&gt; Slave</a></h2>
<p>If the master wants to send data to the slave:</p>
<p align="center">
  <img class="white_bg" height=180 title="I2C bus" src="https://upload.wikimedia.org/wikipedia/commons/3/3e/I2C.svg">
</p>
<ol>
<li>Master: Broadcast START</li>
<li>M: Broadcast slave address (7 bits) + the R/W (8th) bit set to WRITE</li>
<li>Slave: Responds ACK (ACKnowledgement)</li>
<li>M: Send one byte</li>
<li>S: Responds ACK</li>
<li>Repeat steps 4 and 5 zero or more times</li>
<li>M: Broadcast STOP OR (broadcast RESTART and go back to (2))</li>
</ol>
<blockquote>
<p><strong>NOTE</strong> The slave address could have been 10 bits instead of 7 bits long. Nothing else would have
changed.</p>
</blockquote>
<h2 id="master---slave-1"><a class="header" href="#master---slave-1">Master &lt;- Slave</a></h2>
<p>If the master wants to read data from the slave:</p>
<p align="center">
<img class="white_bg" height=180 title="I2C bus" src="https://upload.wikimedia.org/wikipedia/commons/3/3e/I2C.svg">
</p>
<ol>
<li>M: Broadcast START</li>
<li>M: Broadcast slave address (7 bits) + the R/W (8th) bit set to READ</li>
<li>S: Responds with ACK</li>
<li>S: Send byte</li>
<li>M: Responds with ACK</li>
<li>Repeat steps 4 and 5 zero or more times</li>
<li>M: Broadcast STOP OR (broadcast RESTART and go back to (2))</li>
</ol>
<blockquote>
<p><strong>NOTE</strong> The slave address could have been 10 bits instead of 7 bits long. Nothing else would have
changed.</p>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h1 id="lsm303agr"><a class="header" href="#lsm303agr">LSM303AGR</a></h1>
<p>Both of the motion sensors on the micro:bit, the magnetometer and the accelerometer, are packaged in a single
component: the LSM303AGR integrated circuit. These two sensors can be accessed via an I2C bus. Each
sensor behaves like an I2C slave and has a <em>different</em> address.</p>
<p>Each sensor has its own memory where it stores the results of sensing its environment. Our
interaction with these sensors will mainly involve reading their memory.</p>
<p>The memory of these sensors is modeled as byte addressable registers. These sensors can be
configured too; that's done by writing to their registers. So, in a sense, these sensors are very
similar to the peripherals <em>inside</em> the microcontroller. The difference is that their registers are
not mapped into the microcontrollers' memory. Instead, their registers have to be accessed via the
I2C bus.</p>
<p>The main source of information about the LSM303AGR is its <a href="https://www.st.com/resource/en/datasheet/lsm303agr.pdf">Data Sheet</a>. Read through it to see how
one can read the sensors' registers. That part is in:</p>
<blockquote>
<p>Section 6.1.1 I2C Operation - Page 38 - LSM303AGR Data Sheet</p>
</blockquote>
<p>The other part of the documentation relevant to this book is the description of the registers. That
part is in:</p>
<blockquote>
<p>Section 8 Register description - Page 46 - LSM303AGR Data Sheet</p>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h1 id="read-a-single-register"><a class="header" href="#read-a-single-register">Read a single register</a></h1>
<p>Let's put all that theory into practice!</p>
<p>First things first we need to know the slave addresses of both the accelerometer
and the magnetometer inside the chip, these can be found in the LSM303AGR's
datasheet on page 39 and are:</p>
<ul>
<li>0011001 for the accelerometer</li>
<li>0011110 for the magnetometer</li>
</ul>
<blockquote>
<p><strong>NOTE</strong> Remember that these are only the 7 leading bits of the address,
the 8th bit is going to be the bit that determines whether we are
performing a read or write.</p>
</blockquote>
<p>Next up we'll need a register to read from. Lots of I2C chips out there will
provide some sort of device identification register for their masters to read.
This is done since considering the thousands (or even millions) of I2C chips
out there it is highly likely that at some point two chips with the same address
will end up being built (after all the address is &quot;only&quot; 7 bit wide). With
this device ID register a driver could then make sure that it is indeed talking
to a LSM303AGR and not some other chip that just happens to have the same address.
As you can read in the LSM303AGR's datasheet (specifically on page 46 and 61)
it does provide two registers called <code>WHO_AM_I_A</code> at address <code>0x0f</code> and <code>WHO_AM_I_M</code>
at address <code>0x4f</code> which contain some bit patterns that are unique to the device
(The A is as in accelerometer and the M is as in magnetometer).</p>
<p>The only thing missing now is the software part, i.e. which API of the <code>microbit</code>/the HAL
crates we should use for this. However, if you read through the datasheet of the nRF chip
you are using you will soon find out that they don't actually have an I2C peripheral.
Luckily for us though, they have I2C-compatible ones called TWI (Two Wire Interface)
and TWIM (depending on which chip you use, just like UART and UARTE).</p>
<p>Now if we put the documentation of the <a href="https://docs.rs/microbit-v2/0.11.0/microbit/hal/twim/index.html"><code>twi(m)</code> module</a> from the <code>microbit</code> crate
together with all the other information we have gathered so far we'll end up with this
piece of code to read out and print the two device IDs:</p>
<pre><pre class="playground"><code class="language-rust">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use rtt_target::{rtt_init_print, rprintln};
use panic_rtt_target as _;

use microbit::hal::prelude::*;

#[cfg(feature = &quot;v1&quot;)]
use microbit::{
    hal::twi,
    pac::twi0::frequency::FREQUENCY_A,
};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{
    hal::twim,
    pac::twim0::frequency::FREQUENCY_A,
};

const ACCELEROMETER_ADDR: u8 = 0b0011001;
const MAGNETOMETER_ADDR: u8 = 0b0011110;

const ACCELEROMETER_ID_REG: u8 = 0x0f;
const MAGNETOMETER_ID_REG: u8 = 0x4f;

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();


    #[cfg(feature = &quot;v1&quot;)]
    let mut i2c = { twi::Twi::new(board.TWI0, board.i2c.into(), FREQUENCY_A::K100) };

    #[cfg(feature = &quot;v2&quot;)]
    let mut i2c = { twim::Twim::new(board.TWIM0, board.i2c_internal.into(), FREQUENCY_A::K100) };

    let mut acc = [0];
    let mut mag = [0];

    // First write the address + register onto the bus, then read the chip's responses
    i2c.write_read(ACCELEROMETER_ADDR, &amp;[ACCELEROMETER_ID_REG], &amp;mut acc).unwrap();
    i2c.write_read(MAGNETOMETER_ADDR, &amp;[MAGNETOMETER_ID_REG], &amp;mut mag).unwrap();

    rprintln!(&quot;The accelerometer chip's id is: {:#b}&quot;, acc[0]);
    rprintln!(&quot;The magnetometer chip's id is: {:#b}&quot;, mag[0]);

    loop {}
}
</code></pre></pre>
<p>Apart from the initialization, this piece of code should be straight forward if you
understood the I2C protocol as described before. The initialization here works similarly
to the one from the UART chapter.
We pass the peripheral as well as the pins that are used to communicate with the chip to the constructor; and then the frequency we wish the bus to operate on, in this case 100 kHz (<code>K100</code>).</p>
<h2 id="testing-it-2"><a class="header" href="#testing-it-2">Testing it</a></h2>
<p>As always you have to modify <code>Embed.toml</code> to fit your MCU and can then use:</p>
<pre><code class="language-console"># For micro:bit v2
$ cargo embed --features v2 --target thumbv7em-none-eabihf

# For micro:bit v1
$ cargo embed --features v1 --target thumbv6m-none-eabi
</code></pre>
<p>in order to test our little example program.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="using-a-driver"><a class="header" href="#using-a-driver">Using a driver</a></h1>
<p>As we already discussed in chapter 5 <code>embedded-hal</code> provides abstractions
which can be used to write platform independent code that can interact with
hardware. In fact all the methods we have used to interact with hardware
in chapter 7 and up until now in chapter 8 were from traits, defined by <code>embedded-hal</code>.
Now we'll make actual use of the traits <code>embedded-hal</code> provides for the first time.</p>
<p>It would be pointless to implement a driver for our LSM303AGR for every platform
embedded Rust supports (and new ones that might eventually pop up). To avoid this a driver
can be written that consumes generic types that implement <code>embedded-hal</code> traits in order to provide
a platform agnostic version of a driver. Luckily for us this has already been done in the
<a href="https://crates.io/crates/lsm303agr"><code>lsm303agr</code></a> crate. Hence reading the actual accelerometer and magnetometer values will now
be basically a plug and play experience (plus reading a bit of documentation). In fact the <code>crates.io</code>
page already provides us with everything we need to know in order to read accelerometer data but using a Raspberry Pi. We'll
just have to adapt it to our chip:</p>
<pre><pre class="playground"><code class="language-rust">use linux_embedded_hal::I2cdev;
use lsm303agr::{AccelOutputDataRate, Lsm303agr};

fn main() {
    let dev = I2cdev::new(&quot;/dev/i2c-1&quot;).unwrap();
    let mut sensor = Lsm303agr::new_with_i2c(dev);
    sensor.init().unwrap();
    sensor.set_accel_odr(AccelOutputDataRate::Hz50).unwrap();
    loop {
        if sensor.accel_status().unwrap().xyz_new_data {
            let data = sensor.accel_data().unwrap();
            println!(&quot;Acceleration: x {} y {} z {}&quot;, data.x, data.y, data.z);
        }
    }
}
</code></pre></pre>
<p>Because we already know how to create an instance of an object that implements
the <a href="https://docs.rs/embedded-hal/0.2.6/embedded_hal/blocking/i2c/index.html"><code>embedded_hal::blocking::i2c</code></a> traits from the <a href="08-i2c/read-a-single-register.html">previous page</a>, this is quite trivial:</p>
<pre><pre class="playground"><code class="language-rust">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use rtt_target::{rtt_init_print, rprintln};
use panic_rtt_target as _;

#[cfg(feature = &quot;v1&quot;)]
use microbit::{
    hal::twi,
    pac::twi0::frequency::FREQUENCY_A,
};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{
    hal::twim,
    pac::twim0::frequency::FREQUENCY_A,
};

use lsm303agr::{
    AccelOutputDataRate, Lsm303agr,
};

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();


    #[cfg(feature = &quot;v1&quot;)]
    let i2c = { twi::Twi::new(board.TWI0, board.i2c.into(), FREQUENCY_A::K100) };

    #[cfg(feature = &quot;v2&quot;)]
    let i2c = { twim::Twim::new(board.TWIM0, board.i2c_internal.into(), FREQUENCY_A::K100) };

    // Code from documentation
    let mut sensor = Lsm303agr::new_with_i2c(i2c);
    sensor.init().unwrap();
    sensor.set_accel_odr(AccelOutputDataRate::Hz50).unwrap();
    loop {
        if sensor.accel_status().unwrap().xyz_new_data {
            let data = sensor.accel_data().unwrap();
            // RTT instead of normal print
            rprintln!(&quot;Acceleration: x {} y {} z {}&quot;, data.x, data.y, data.z);
        }
    }
}
</code></pre></pre>
<p>Just like the last snippet you should just be able to try this out like this:</p>
<pre><code class="language-console"># For micro:bit v2
$ cargo embed --features v2 --target thumbv7em-none-eabihf

# For micro:bit v1
$ cargo embed --features v1 --target thumbv6m-none-eabi
</code></pre>
<p>Furthermore if you (physically) move around your micro:bit a little you should see the
acceleration numbers that are being printed change.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="the-challenge-1"><a class="header" href="#the-challenge-1">The challenge</a></h1>
<p>The challenge for this chapter is, to build a small application that
communicates with the outside world via the serial interface introduced
in the last chapter. It should be able to receive the commands &quot;magnetometer&quot;
as well as &quot;accelerometer&quot; and then print the corresponding sensor data
in response. This time no template code will be provided since all you need
is already provided in the <a href="08-i2c/../07-uart/index.html">UART</a> and this chapter. However, here are a few clues:</p>
<ul>
<li>You might be interested in <code>core::str::from_utf8</code> to convert the bytes in the buffer to a <code>&amp;str</code>, since we need to compare with <code>&quot;magnetometer&quot;</code> and <code>&quot;accelerometer&quot;</code>.</li>
<li>You will (obviously) have to read the documentation of the magnetometer API, however
it's more or less equivalent to the accelerometer one</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="my-solution-2"><a class="header" href="#my-solution-2">My solution</a></h1>
<pre><pre class="playground"><code class="language-rust">#![no_main]
#![no_std]

use core::str;

use cortex_m_rt::entry;
use rtt_target::rtt_init_print;
use panic_rtt_target as _;

#[cfg(feature = &quot;v1&quot;)]
use microbit::{
    hal::twi,
    pac::twi0::frequency::FREQUENCY_A,
    hal::uart,
    hal::uart::{Baudrate, Parity},
};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{
    hal::twim,
    pac::twim0::frequency::FREQUENCY_A,
    hal::uarte,
    hal::uarte::{Baudrate, Parity},
};

use microbit::hal::prelude::*;
use lsm303agr::{AccelOutputDataRate, MagOutputDataRate, Lsm303agr};
use heapless::Vec;
use nb::block;
use core::fmt::Write;

#[cfg(feature = &quot;v2&quot;)]
mod serial_setup;
#[cfg(feature = &quot;v2&quot;)]
use serial_setup::UartePort;

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();

    #[cfg(feature = &quot;v1&quot;)]
    let mut serial = {
        uart::Uart::new(
            board.UART0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        )
    };

    #[cfg(feature = &quot;v2&quot;)]
    let mut serial = {
        let serial = uarte::Uarte::new(
            board.UARTE0,
            board.uart.into(),
            Parity::EXCLUDED,
            Baudrate::BAUD115200,
        );
        UartePort::new(serial)
    };

    #[cfg(feature = &quot;v1&quot;)]
    let i2c = { twi::Twi::new(board.TWI0, board.i2c.into(), FREQUENCY_A::K100) };

    #[cfg(feature = &quot;v2&quot;)]
    let i2c = { twim::Twim::new(board.TWIM0, board.i2c_internal.into(), FREQUENCY_A::K100) };

    let mut sensor = Lsm303agr::new_with_i2c(i2c);
    sensor.init().unwrap();
    sensor.set_accel_odr(AccelOutputDataRate::Hz50).unwrap();
    sensor.set_mag_odr(MagOutputDataRate::Hz50).unwrap();
    let mut sensor = sensor.into_mag_continuous().ok().unwrap();

    loop {
        let mut buffer: Vec&lt;u8, 32&gt; = Vec::new();

        loop {
            let byte = block!(serial.read()).unwrap();

            if byte == 13 {
                break;
            }

            if buffer.push(byte).is_err() {
                write!(serial, &quot;error: buffer full\r\n&quot;).unwrap();
                break;
            }
        }

        if str::from_utf8(&amp;buffer).unwrap().trim() == &quot;accelerometer&quot; {
            while !sensor.accel_status().unwrap().xyz_new_data  {
            }

            let data = sensor.accel_data().unwrap();
            write!(serial, &quot;Accelerometer: x {} y {} z {}\r\n&quot;, data.x, data.y, data.z).unwrap();
        } else if str::from_utf8(&amp;buffer).unwrap().trim() == &quot;magnetometer&quot; {
            while !sensor.mag_status().unwrap().xyz_new_data  {
            }

            let data = sensor.mag_data().unwrap();
            write!(serial, &quot;Magnetometer: x {} y {} z {}\r\n&quot;, data.x, data.y, data.z).unwrap();
        } else {
            write!(serial, &quot;error: command not detected\r\n&quot;).unwrap();
        }
    }
}

</code></pre></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="led-compass"><a class="header" href="#led-compass">LED compass</a></h1>
<p>In this section, we'll implement a compass using the LEDs on the micro:bit. Like proper compasses, our LED
compass must point north somehow. It will do that by turning on one of its outer LEDs; the LED turned on
should point towards north.</p>
<p>Magnetic fields have both a magnitude, measured in Gauss or Teslas, and a <em>direction</em>. The
magnetometer on the micro:bit measures both the magnitude and the direction of an external magnetic field
but it reports back the <em>decomposition</em> of said field along <em>its axes</em>.</p>
<p>The magnetometer has three axes associated to it. The X and Y axes basically span the plane that is the floor.
The Z axis is pointing &quot;out&quot; of the floor, so upwards.</p>
<p>You should already be able to write a program that continuously prints the magnetometer
data on the RTT console from the <a href="09-led-compass/../08-i2c/index.html">I2C chapter</a>. After you wrote that
program, locate where north is at your current location. Then line up your micro:bit with
that direction and observe how the sensor's measurements look.</p>
<p>Now rotate the board 90 degrees while keeping it parallel to the ground. What X, Y and Z values do
you see this time? Then rotate it 90 degrees again. What values do you see?</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="calibration"><a class="header" href="#calibration">Calibration</a></h1>
<p>One very important thing to do before using a sensor and trying to develop
an application using it is verifying that it's output is actually correct.
If this does not happen to be the case we need to calibrate the sensor
(alternatively it could also be broken but that's rather unlikely in this case).</p>
<p>In my case on two different micro:bit's the magnetometer, without calibration,
was quite a bit off of what it is supposed to measure. Hence for the purposes
of this chapter we will just assume that the sensor has to be calibrated.</p>
<p>The calibration involves quite a bit of math (matrices) so we won't cover it here but this
<a href="https://www.st.com/resource/en/design_tip/dt0103-compensating-for-magnetometer-installation-error-and-hardiron-effects-using-accelerometerassisted-2d-calibration-stmicroelectronics.pdf">Design Note</a> describes the procedure if you are interested. </p>
<p>Luckily for us though the group that built the original software for the
micro:bit already implemented a calibration mechanism in C++ over <a href="https://github.com/lancaster-university/codal-microbit-v2/blob/006abf5566774fbcf674c0c7df27e8a9d20013de/source/MicroBitCompassCalibrator.cpp">here</a>.</p>
<p>You can find a translation of it to Rust in <code>src/calibration.rs</code>. The usage
is demonstrated in the default <code>src/main.rs</code> file. The way the calibration
works is illustrated in this video:</p>
<p align="center">
<video src="https://video.microbit.org/support/compass+calibration.mp4" loop autoplay>
</p>
<p>You have to basically tilt the micro:bit until all the LEDs on the LED matrix light up.</p>
<p>If you do not want to play the game every time you restart your application during development
feel free to modify the <code>src/main.rs</code> template to just use the same static calibration
once you got the first one.</p>
<p>Now where we got the sensor calibration out of the way let's look into
actually building this application!</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="take-1"><a class="header" href="#take-1">Take 1</a></h1>
<p>What's the simplest way in which we can implement the LED compass, even if it's not perfect?</p>
<p>For starters, we'd only care about the X and Y components of the magnetic field because when you
look at a compass you always hold it in horizontal position and thus the compass is in the XY plane.</p>
<p align="center">
<img class="white_bg" title="Quadrants" src="09-led-compass/../assets/quadrants.png">
</p>
<p>If we only looked at the signs of the X and Y components we could determine to which quadrant the
magnetic field belongs to. Now the question of course is which direction (north, north-east, etc.)
do the 4 quadrants represent. In order to figure this out we can just rotate the micro:bit and observe
how the quadrant changes whenever we point in another direction.</p>
<p>After experimenting a bit we can find out that if we point the micro:bit in e.g. north-east direction,
both the X and the Y component are always positive. Based on this information you should be able to
figure out which direction the other quadrants represent.</p>
<p>Once you figured out the relation between quadrant and direction you should be able to
complete the template from below.</p>
<pre><pre class="playground"><code class="language-rust">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use panic_rtt_target as _;
use rtt_target::{rprintln, rtt_init_print};

mod calibration;
use crate::calibration::calc_calibration;
use crate::calibration::calibrated_measurement;

mod led;
use led::Direction;

use microbit::{display::blocking::Display, hal::Timer};

#[cfg(feature = &quot;v1&quot;)]
use microbit::{hal::twi, pac::twi0::frequency::FREQUENCY_A};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{hal::twim, pac::twim0::frequency::FREQUENCY_A};

use lsm303agr::{AccelOutputDataRate, Lsm303agr, MagOutputDataRate};

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();

    #[cfg(feature = &quot;v1&quot;)]
    let i2c = { twi::Twi::new(board.TWI0, board.i2c.into(), FREQUENCY_A::K100) };

    #[cfg(feature = &quot;v2&quot;)]
    let i2c = { twim::Twim::new(board.TWIM0, board.i2c_internal.into(), FREQUENCY_A::K100) };

    let mut timer = Timer::new(board.TIMER0);
    let mut display = Display::new(board.display_pins);

    let mut sensor = Lsm303agr::new_with_i2c(i2c);
    sensor.init().unwrap();
    sensor.set_mag_odr(MagOutputDataRate::Hz10).unwrap();
    sensor.set_accel_odr(AccelOutputDataRate::Hz10).unwrap();
    let mut sensor = sensor.into_mag_continuous().ok().unwrap();

    let calibration = calc_calibration(&amp;mut sensor, &amp;mut display, &amp;mut timer);
    rprintln!(&quot;Calibration: {:?}&quot;, calibration);
    rprintln!(&quot;Calibration done, entering busy loop&quot;);
    loop {
        while !sensor.mag_status().unwrap().xyz_new_data {}
        let mut data = sensor.mag_data().unwrap();
        data = calibrated_measurement(data, &amp;calibration);

        let dir = match (data.x &gt; 0, data.y &gt; 0) {
            // Quadrant ???
            (true, true) =&gt; Direction::NorthEast,
            // Quadrant ???
            (false, true) =&gt; panic!(&quot;TODO&quot;),
            // Quadrant ???
            (false, false) =&gt; panic!(&quot;TODO&quot;),
            // Quadrant ???
            (true, false) =&gt; panic!(&quot;TODO&quot;),
        };

        // use the led module to turn the direction into an LED arrow
        // and the led display functions from chapter 5 to display the
        // arrow
    }
}
</code></pre></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="solution-1"><a class="header" href="#solution-1">Solution 1</a></h1>
<pre><pre class="playground"><code class="language-rust">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use panic_rtt_target as _;
use rtt_target::{rprintln, rtt_init_print};

mod calibration;
use crate::calibration::calc_calibration;
use crate::calibration::calibrated_measurement;

mod led;
use crate::led::Direction;
use crate::led::direction_to_led;

use microbit::{display::blocking::Display, hal::Timer};

#[cfg(feature = &quot;v1&quot;)]
use microbit::{hal::twi, pac::twi0::frequency::FREQUENCY_A};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{hal::twim, pac::twim0::frequency::FREQUENCY_A};

use lsm303agr::{AccelOutputDataRate, Lsm303agr, MagOutputDataRate};

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();

    #[cfg(feature = &quot;v1&quot;)]
    let i2c = { twi::Twi::new(board.TWI0, board.i2c.into(), FREQUENCY_A::K100) };

    #[cfg(feature = &quot;v2&quot;)]
    let i2c = { twim::Twim::new(board.TWIM0, board.i2c_internal.into(), FREQUENCY_A::K100) };

    let mut timer = Timer::new(board.TIMER0);
    let mut display = Display::new(board.display_pins);

    let mut sensor = Lsm303agr::new_with_i2c(i2c);
    sensor.init().unwrap();
    sensor.set_mag_odr(MagOutputDataRate::Hz10).unwrap();
    sensor.set_accel_odr(AccelOutputDataRate::Hz10).unwrap();
    let mut sensor = sensor.into_mag_continuous().ok().unwrap();

    let calibration = calc_calibration(&amp;mut sensor, &amp;mut display, &amp;mut timer);
    rprintln!(&quot;Calibration: {:?}&quot;, calibration);
    rprintln!(&quot;Calibration done, entering busy loop&quot;);
    loop {
        while !sensor.mag_status().unwrap().xyz_new_data {}
        let mut data = sensor.mag_data().unwrap();
        data = calibrated_measurement(data, &amp;calibration);

        let dir = match (data.x &gt; 0, data.y &gt; 0) {
            // Quadrant I
            (true, true) =&gt; Direction::NorthEast,
            // Quadrant II
            (false, true) =&gt; Direction::NorthWest,
            // Quadrant III
            (false, false) =&gt; Direction::SouthWest,
            // Quadrant IV
            (true, false) =&gt; Direction::SouthEast,
        };

        // use the led module to turn the direction into an LED arrow
        // and the led display functions from chapter 5 to display the
        // arrow
        display.show(&amp;mut timer, direction_to_led(dir), 100);
    }
}
</code></pre></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="take-2"><a class="header" href="#take-2">Take 2</a></h1>
<p>This time, we'll use math to get the precise angle that the magnetic field forms with the X and Y
axes of the magnetometer.</p>
<p>We'll use the <code>atan2</code> function. This function returns an angle in the <code>-PI</code> to <code>PI</code> range. The
graphic below shows how this angle is measured:</p>
<p align="center">
<img class="white_bg" title="atan2" src="https://upload.wikimedia.org/wikipedia/commons/0/03/Atan2_60.svg">
</p>
<p>Although not explicitly shown in this graph the X axis points to the right and the Y axis points up.</p>
<p>Here's the starter code. <code>theta</code>, in radians, has already been computed. You need to pick which LED
to turn on based on the value of <code>theta</code>.</p>
<pre><code class="language-rs">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use panic_rtt_target as _;
use rtt_target::{rprintln, rtt_init_print};

mod calibration;
use crate::calibration::calc_calibration;
use crate::calibration::calibrated_measurement;

mod led;
use crate::led::Direction;
use crate::led::direction_to_led;

// You'll find this useful ;-)
use core::f32::consts::PI;
use libm::atan2f;

use microbit::{display::blocking::Display, hal::Timer};

#[cfg(feature = &quot;v1&quot;)]
use microbit::{hal::twi, pac::twi0::frequency::FREQUENCY_A};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{hal::twim, pac::twim0::frequency::FREQUENCY_A};

use lsm303agr::{AccelOutputDataRate, Lsm303agr, MagOutputDataRate};

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();

    #[cfg(feature = &quot;v1&quot;)]
    let i2c = { twi::Twi::new(board.TWI0, board.i2c.into(), FREQUENCY_A::K100) };

    #[cfg(feature = &quot;v2&quot;)]
    let i2c = { twim::Twim::new(board.TWIM0, board.i2c_internal.into(), FREQUENCY_A::K100) };

    let mut timer = Timer::new(board.TIMER0);
    let mut display = Display::new(board.display_pins);

    let mut sensor = Lsm303agr::new_with_i2c(i2c);
    sensor.init().unwrap();
    sensor.set_mag_odr(MagOutputDataRate::Hz10).unwrap();
    sensor.set_accel_odr(AccelOutputDataRate::Hz10).unwrap();
    let mut sensor = sensor.into_mag_continuous().ok().unwrap();

    let calibration = calc_calibration(&amp;mut sensor, &amp;mut display, &amp;mut timer);
    rprintln!(&quot;Calibration: {:?}&quot;, calibration);
    rprintln!(&quot;Calibration done, entering busy loop&quot;);
    loop {
        while !sensor.mag_status().unwrap().xyz_new_data {}
        let mut data = sensor.mag_data().unwrap();
        data = calibrated_measurement(data, &amp;calibration);

        // use libm's atan2f since this isn't in core yet
        let theta = atan2f(data.y as f32, data.x as f32);

        // Figure out the direction based on theta
        let dir = Direction::NorthEast;

        display.show(&amp;mut timer, direction_to_led(dir), 100);
    }
}
</code></pre>
<p>Suggestions/tips:</p>
<ul>
<li>A whole circle rotation equals 360 degrees.</li>
<li><code>PI</code> radians is equivalent to 180 degrees.</li>
<li>If <code>theta</code> was zero, which direction are you pointing at?</li>
<li>If <code>theta</code> was, instead, very close to zero, which direction are you pointing at?</li>
<li>If <code>theta</code> kept increasing, at what value would you change the direction</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="solution-2"><a class="header" href="#solution-2">Solution 2</a></h1>
<pre><pre class="playground"><code class="language-rust">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use panic_rtt_target as _;
use rtt_target::{rprintln, rtt_init_print};

mod calibration;
use crate::calibration::calc_calibration;
use crate::calibration::calibrated_measurement;

mod led;
use crate::led::Direction;
use crate::led::direction_to_led;

// You'll find this useful ;-)
use core::f32::consts::PI;
use libm::atan2f;

use microbit::{display::blocking::Display, hal::Timer};

#[cfg(feature = &quot;v1&quot;)]
use microbit::{hal::twi, pac::twi0::frequency::FREQUENCY_A};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{hal::twim, pac::twim0::frequency::FREQUENCY_A};

use lsm303agr::{AccelOutputDataRate, Lsm303agr, MagOutputDataRate};

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();

    #[cfg(feature = &quot;v1&quot;)]
    let i2c = { twi::Twi::new(board.TWI0, board.i2c.into(), FREQUENCY_A::K100) };

    #[cfg(feature = &quot;v2&quot;)]
    let i2c = { twim::Twim::new(board.TWIM0, board.i2c_internal.into(), FREQUENCY_A::K100) };

    let mut timer = Timer::new(board.TIMER0);
    let mut display = Display::new(board.display_pins);

    let mut sensor = Lsm303agr::new_with_i2c(i2c);
    sensor.init().unwrap();
    sensor.set_mag_odr(MagOutputDataRate::Hz10).unwrap();
    sensor.set_accel_odr(AccelOutputDataRate::Hz10).unwrap();
    let mut sensor = sensor.into_mag_continuous().ok().unwrap();

    let calibration = calc_calibration(&amp;mut sensor, &amp;mut display, &amp;mut timer);
    rprintln!(&quot;Calibration: {:?}&quot;, calibration);
    rprintln!(&quot;Calibration done, entering busy loop&quot;);
    loop {
        while !sensor.mag_status().unwrap().xyz_new_data {}
        let mut data = sensor.mag_data().unwrap();
        data = calibrated_measurement(data, &amp;calibration);

        // use libm's atan2f since this isn't in core yet
        let theta = atan2f(data.y as f32, data.x as f32);

        // Figure out the direction based on theta
        let dir = if theta &lt; -7. * PI / 8. {
            Direction::West
        } else if theta &lt; -5. * PI / 8. {
            Direction::SouthWest
        } else if theta &lt; -3. * PI / 8. {
            Direction::South
        } else if theta &lt; -PI / 8. {
            Direction::SouthEast
        } else if theta &lt; PI / 8. {
            Direction::East
        } else if theta &lt; 3. * PI / 8. {
            Direction::NorthEast
        } else if theta &lt; 5. * PI / 8. {
            Direction::North
        } else if theta &lt; 7. * PI / 8. {
            Direction::NorthWest
        } else {
            Direction::West
        };

        display.show(&amp;mut timer, direction_to_led(dir), 100);
    }
}
</code></pre></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="magnitude"><a class="header" href="#magnitude">Magnitude</a></h1>
<p>We have been working with the direction of the magnetic field but what is its real magnitude?
According to the documentation about the <a href="https://docs.rs/lsm303agr/0.2.2/lsm303agr/struct.Lsm303agr.html#method.mag_data"><code>mag_data()</code></a> function the <code>x</code> <code>y</code> <code>z</code> values we are
getting are in nanotesla. That means the only thing we have to compute in order to get the
magnitude of the magnetic field in nanotesla is the magnitude of the 3D vector that our <code>x</code> <code>y</code> <code>z</code>
values describe. As you might remember from school this is simply:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// core doesn't have this function yet so we use libm, just like with
// atan2f from before.
use libm::sqrtf;
let magnitude = sqrtf(x * x + y * y + z * z);
<span class="boring">}
</span></code></pre></pre>
<p>Putting all this together in a program:</p>
<pre><pre class="playground"><code class="language-rust">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use panic_rtt_target as _;
use rtt_target::{rprintln, rtt_init_print};

mod calibration;
use crate::calibration::calc_calibration;
use crate::calibration::calibrated_measurement;

use libm::sqrtf;

use microbit::{display::blocking::Display, hal::Timer};

#[cfg(feature = &quot;v1&quot;)]
use microbit::{hal::twi, pac::twi0::frequency::FREQUENCY_A};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{hal::twim, pac::twim0::frequency::FREQUENCY_A};

use lsm303agr::{AccelOutputDataRate, Lsm303agr, MagOutputDataRate};

#[entry]
fn main() -&gt; ! {
    rtt_init_print!();
    let board = microbit::Board::take().unwrap();

    #[cfg(feature = &quot;v1&quot;)]
    let i2c = { twi::Twi::new(board.TWI0, board.i2c.into(), FREQUENCY_A::K100) };

    #[cfg(feature = &quot;v2&quot;)]
    let i2c = { twim::Twim::new(board.TWIM0, board.i2c_internal.into(), FREQUENCY_A::K100) };

    let mut timer = Timer::new(board.TIMER0);
    let mut display = Display::new(board.display_pins);

    let mut sensor = Lsm303agr::new_with_i2c(i2c);
    sensor.init().unwrap();
    sensor.set_mag_odr(MagOutputDataRate::Hz10).unwrap();
    sensor.set_accel_odr(AccelOutputDataRate::Hz10).unwrap();
    let mut sensor = sensor.into_mag_continuous().ok().unwrap();

    let calibration = calc_calibration(&amp;mut sensor, &amp;mut display, &amp;mut timer);
    rprintln!(&quot;Calibration: {:?}&quot;, calibration);
    rprintln!(&quot;Calibration done, entering busy loop&quot;);
    loop {
        while !sensor.mag_status().unwrap().xyz_new_data {}
        let mut data = sensor.mag_data().unwrap();
        data = calibrated_measurement(data, &amp;calibration);
        let x = data.x as f32;
        let y = data.y as f32;
        let z = data.z as f32;
        let magnitude = sqrtf(x * x + y * y + z * z);
        rprintln!(&quot;{} nT, {} mG&quot;, magnitude, magnitude/100.0);
    }
}
</code></pre></pre>
<p>This program will report the magnitude (strength) of the magnetic field in nanotesla (<code>nT</code>) and milligauss (<code>mG</code>). The
magnitude of the Earth's magnetic field is in the range of <code>250 mG</code> to <code>650 mG</code> (the magnitude
varies depending on your geographical location) so you should see a value in that range or close to
that range -- I see a magnitude of around <code>340 mG</code>.</p>
<p>Some questions:</p>
<p>Without moving the board, what value do you see? Do you always see the same value?</p>
<p>If you rotate the board, does the magnitude change? Should it change?</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="punch-o-meter"><a class="header" href="#punch-o-meter">Punch-o-meter</a></h1>
<p>In this section we'll be playing with the accelerometer that's in the board.</p>
<p>What are we building this time? A punch-o-meter! We'll be measuring the power of your jabs. Well,
actually the maximum acceleration that you can reach because acceleration is what accelerometers
measure. Strength and acceleration are proportional though so it's a good approximation.</p>
<p>As we already know from previous chapters the accelerometer is built inside the LSM303AGR package.
And just like the magnetometer, it is accessible using the I2C bus. It also has the same coordinate
system as the magnetometer.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="gravity-is-up"><a class="header" href="#gravity-is-up">Gravity is up?</a></h1>
<p>What's the first thing we'll do?</p>
<p>Perform a sanity check!</p>
<p>You should already be able to write a program that continuously prints the accelerometer
data on the RTT console from the <a href="10-punch-o-meter/../08-i2c/index.html">I2C chapter</a>. Do you observe something
interesting even when holding the board parallel to the floor with the LED side facing down?</p>
<p>What you should see like this is that both the X and Y values are rather close to 0, while the
Z value is at around 1000. Which is weird because the board is not moving yet its acceleration is
non-zero. What's going on? This must be related to the gravity, right? Because the acceleration of
gravity is <code>1 g</code> (aha, <code>1 g</code> = 1000 from the accelerometer). But the gravity pulls objects downwards
so the acceleration along the Z axis should be negative not positive</p>
<p>Did the program get the Z axis backwards? Nope, you can test rotating the board to align the gravity
to the X or Y axis but the acceleration measured by the accelerometer is always pointing up.</p>
<p>What happens here is that the accelerometer is measuring the <em>proper acceleration</em> of the board not
the acceleration <em>you</em> are observing. This proper acceleration is the acceleration of the board as
seen from an observer that's in free fall. An observer that's in free fall is moving toward the
center of the Earth with an acceleration of <code>1g</code>; from its point of view the board is actually
moving upwards (away from the center of the Earth) with an acceleration of <code>1g</code>. And that's why the
proper acceleration is pointing up. This also means that if the board was in free fall, the
accelerometer would report a proper acceleration of zero. Please, don't try that at home.</p>
<p>Yes, physics is hard. Let's move on.</p>
<div style="break-before: page; page-break-before: always;"></div><h1 id="the-challenge-2"><a class="header" href="#the-challenge-2">The challenge</a></h1>
<p>To keep things simple, we'll measure the acceleration only in the X axis while the board remains
horizontal. That way we won't have to deal with subtracting that <em>fictitious</em> <code>1g</code> we observed
before which would be hard because that <code>1g</code> could have X Y Z components depending on how the board
is oriented.</p>
<p>Here's what the punch-o-meter must do:</p>
<ul>
<li>By default, the app is not &quot;observing&quot; the acceleration of the board.</li>
<li>When a significant X acceleration is detected (i.e. the acceleration goes above some threshold),
the app should start a new measurement.</li>
<li>During that measurement interval, the app should keep track of the maximum acceleration observed</li>
<li>After the measurement interval ends, the app must report the maximum acceleration observed. You
can report the value using the <code>rprintln!</code> macro.</li>
</ul>
<p>Give it a try and let me know how hard you can punch <code>;-)</code>.</p>
<blockquote>
<p><strong>NOTE</strong> There are two additional APIs that should be useful for this task we haven't discussed yet.
First the <a href="https://docs.rs/lsm303agr/0.2.2/lsm303agr/struct.Lsm303agr.html#method.set_accel_scale"><code>set_accel_scale</code></a> one which you need to measure high g values.
Secondly the <a href="https://docs.rs/embedded-hal/0.2.6/embedded_hal/timer/trait.CountDown.html"><code>Countdown</code></a> trait from <code>embedded_hal</code>. If you decide to use this to keep your measurement
intervals you will have to pattern match on the <a href="https://docs.rs/nb/1.0.0/nb/type.Result.html"><code>nb::Result</code></a> type instead of using the <code>block!</code> macro
we have seen in previous chapters.</p>
</blockquote>
<div style="break-before: page; page-break-before: always;"></div><h1 id="my-solution-3"><a class="header" href="#my-solution-3">My solution</a></h1>
<pre><pre class="playground"><code class="language-rust">#![deny(unsafe_code)]
#![no_main]
#![no_std]

use cortex_m_rt::entry;
use rtt_target::{rtt_init_print, rprintln};
use panic_rtt_target as _;

#[cfg(feature = &quot;v1&quot;)]
use microbit::{
    hal::twi,
    pac::twi0::frequency::FREQUENCY_A,
};

#[cfg(feature = &quot;v2&quot;)]
use microbit::{
    hal::twim,
    pac::twim0::frequency::FREQUENCY_A,
};

use lsm303agr::{
    AccelScale, AccelOutputDataRate, Lsm303agr,
};

use microbit::hal::timer::Timer;
use microbit::hal::prelude::*;
use nb::Error;

#[entry]
fn main() -&gt; ! {
    const THRESHOLD: f32 = 0.5;

    rtt_init_print!();
    let board = microbit::Board::take().unwrap();

    #[cfg(feature = &quot;v1&quot;)]
    let i2c = { twi::Twi::new(board.TWI0, board.i2c.into(), FREQUENCY_A::K100) };

    #[cfg(feature = &quot;v2&quot;)]
    let i2c = { twim::Twim::new(board.TWIM0, board.i2c_internal.into(), FREQUENCY_A::K100) };

    let mut countdown = Timer::new(board.TIMER0);
    let mut delay = Timer::new(board.TIMER1);
    let mut sensor = Lsm303agr::new_with_i2c(i2c);
    sensor.init().unwrap();
    sensor.set_accel_odr(AccelOutputDataRate::Hz50).unwrap();
    // Allow the sensor to measure up to 16 G since human punches
    // can actually be quite fast
    sensor.set_accel_scale(AccelScale::G16).unwrap();

    let mut max_g = 0.;
    let mut measuring = false;

    loop {
        while !sensor.accel_status().unwrap().xyz_new_data {}
        // x acceleration in g
        let g_x = sensor.accel_data().unwrap().x as f32 / 1000.0;

        if measuring {
            // Check the status of our contdown
            match countdown.wait() {
                // countdown isn't done yet
                Err(Error::WouldBlock) =&gt; {
                    if g_x &gt; max_g {
                        max_g = g_x;
                    }
                },
                // Countdown is done
                Ok(_) =&gt; {
                    // Report max value
                    rprintln!(&quot;Max acceleration: {}g&quot;, max_g);

                    // Reset
                    max_g = 0.;
                    measuring = false;
                },
                // Since the nrf52 and nrf51 HAL have Void as an error type
                // this path cannot occur, as Void is an empty type
                Err(Error::Other(_)) =&gt; {
                    unreachable!()
                }
            }
        } else {
            // If acceleration goes above a threshold, we start measuring
            if g_x &gt; THRESHOLD {
                rprintln!(&quot;START!&quot;);

                measuring = true;
                max_g = g_x;
                // The documentation notes that the timer works at a frequency
                // of 1 Mhz, so in order to wait for 1 second we have to
                // set it to 1_000_000 ticks.
                countdown.start(1_000_000_u32);
            }
        }
        delay.delay_ms(20_u8);
    }
}
</code></pre></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="whats-left-for-you-to-explore"><a class="header" href="#whats-left-for-you-to-explore">What's left for you to explore</a></h1>
<p>We have barely scratched the surface! There's lots of stuff left for you to
explore.</p>
<blockquote>
<p><strong>NOTE:</strong> If you're reading this, and you'd like to help add examples or
exercises to the Discovery book for any of the items below, or any other
relevant embedded topics, we'd love to have your help!</p>
<p>Please <a href="https://github.com/rust-embedded/discovery/issues/new">open an issue</a> if you would like to help, but need assistance or
mentoring for how to contribute this to the book, or open a Pull Request
adding the information!</p>
</blockquote>
<h2 id="topics-about-embedded-software"><a class="header" href="#topics-about-embedded-software">Topics about embedded software</a></h2>
<p>These topics discuss strategies for writing embedded software. Although many
problems can be solved in different ways, these sections talk about some
strategies, and when they make sense (or don't make sense) to use.</p>
<h3 id="multitasking"><a class="header" href="#multitasking">Multitasking</a></h3>
<p>All our programs executed a single task. How could we achieve multitasking in a
system with no OS, and thus no threads. There are two main approaches to
multitasking: preemptive multitasking and cooperative multitasking.</p>
<p>In preemptive multitasking a task that's currently being executed can, at any point in time, be
<em>preempted</em> (interrupted) by another task. On preemption, the first task will be suspended and the
processor will instead execute the second task. At some point the first task will be resumed.
Microcontrollers provide hardware support for preemption in the form of <em>interrupts</em>.</p>
<p>In cooperative multitasking a task that's being executed will run until it reaches a <em>suspension
point</em>. When the processor reaches that suspension point it will stop executing the current task and
instead go and execute a different task. At some point the first task will be resumed. The main
difference between these two approaches to multitasking is that in cooperative multitasking <em>yields</em>
execution control at <em>known</em> suspension points instead of being forcefully preempted at any point of
its execution.</p>
<h3 id="sleeping"><a class="header" href="#sleeping">Sleeping</a></h3>
<p>All our programs have been continuously polling peripherals to see if there's
anything that needs to be done. However, sometimes there's nothing to be done!
At those times, the microcontroller should &quot;sleep&quot;.</p>
<p>When the processor sleeps, it stops executing instructions and this saves power.
It's almost always a good idea to save power so your microcontroller should be
sleeping as much as possible. But, how does it know when it has to wake up to
perform some action? &quot;Interrupts&quot; (see below for what exactly those are)
are one of the events that wake up the microcontroller but there are others
and the <code>wfi</code> and <code>wfe</code> are the instructions that make the processor &quot;sleep&quot;.</p>
<h2 id="topics-related-to-microcontroller-capabilities"><a class="header" href="#topics-related-to-microcontroller-capabilities">Topics related to microcontroller capabilities</a></h2>
<p>Microcontrollers (like our nRF52/nRF51) have many capabilities. However, many share similar
capabilities that can be used to solve all sorts of different problems.</p>
<p>These topics discuss some of those capabilities, and how they can be used effectively
in embedded development.</p>
<h3 id="direct-memory-access-dma"><a class="header" href="#direct-memory-access-dma">Direct Memory Access (DMA).</a></h3>
<p>This peripheral is a kind of <em>asynchronous</em> <code>memcpy</code>. If you are working with
a micro:bit v2 you have actually already used this, the HAL does this for you
with the UARTE and TWIM peripherals. A DMA peripheral can be used to perform bulk
transfers of data. Either from RAM to RAM, from a peripheral, like a UARTE, to RAM
or from RAM to a peripheral. You can schedule a DMA transfer, like read 256 bytes
from UARTE into this buffer, leave it running in the background and then poll some
register to see if it has completed so you can do other stuff while the transfer
is ongoing. For more information as to how this is implemented you can checkout the
<code>serial_setup</code> module from the UART chapter. If that isn't enough yet you could even
try and dive into the code of the <a href="https://github.com/nrf-rs/nrf-hal"><code>nrf52-hal</code></a>.</p>
<h3 id="interrupts"><a class="header" href="#interrupts">Interrupts</a></h3>
<p>In order to interact with the real world, it is often necessary for the
microcontroller to respond <em>immediately</em> when some kind of event occurs.</p>
<p>Microcontrollers have the ability to be interrupted, meaning when a certain event
occurs, it will stop whatever it is doing at the moment, to instead respond to that
event. This can be very useful when we want to stop a motor when a button is pressed,
or measure a sensor when a timer finishes counting down.</p>
<p>Although these interrupts can be very useful, they can also be a bit difficult
to work with properly. We want to make sure that we respond to events quickly,
but also allow other work to continue as well.</p>
<p>In Rust, we model interrupts similar to the concept of threading on desktop Rust
programs. This means we also must think about the Rust concepts of <code>Send</code> and <code>Sync</code>
when sharing data between our main application, and code that executes as part of
handling an interrupt event.</p>
<h3 id="pulse-width-modulation-pwm"><a class="header" href="#pulse-width-modulation-pwm">Pulse Width Modulation (PWM)</a></h3>
<p>In a nutshell, PWM is turning on something and then turning it off periodically
while keeping some proportion (&quot;duty cycle&quot;) between the &quot;on time&quot; and the &quot;off
time&quot;. When used on a LED with a sufficiently high frequency, this can be used
to dim the LED. A low duty cycle, say 10% on time and 90% off time, will make
the LED very dim wheres a high duty cycle, say 90% on time and 10% off time,
will make the LED much brighter (almost as if it were fully powered).</p>
<p>In general, PWM can be used to control how much <em>power</em> is given to some
electric device. With proper (power) electronics between a microcontroller and
an electrical motor, PWM can be used to control how much power is given to the
motor thus it can be used to control its torque and speed. Then you can add an
angular position sensor and you got yourself a closed loop controller that can
control the position of the motor at different loads.</p>
<p>PWM is already abstracted within the <a href="https://docs.rs/embedded-hal/0.2.6/embedded_hal/trait.Pwm.html"><code>embedded-hal</code> <code>Pwm</code> trait</a> and you will
again find implementations of this in the <a href="https://github.com/nrf-rs/nrf-hal"><code>nrf52-hal</code></a>.</p>
<h3 id="digital-inputs"><a class="header" href="#digital-inputs">Digital inputs</a></h3>
<p>We have used the microcontroller pins as digital outputs, to drive LEDs. But
these pins can also be configured as digital inputs. As digital inputs, these
pins can read the binary state of switches (on/off) or buttons (pressed/not
pressed).</p>
<p>Again digital inputs are abstracted within the <a href="https://docs.rs/embedded-hal/0.2.6/embedded_hal/digital/v2/trait.InputPin.html"><code>embedded-hal</code> <code>InputPin</code> trait</a>
and of course the <a href="https://github.com/nrf-rs/nrf-hal"><code>nrf52-hal</code></a> does have an implementation for them.</p>
<p>(<em>spoilers</em> reading the binary state of switches / buttons is not as
straightforward as it sounds ;-) )</p>
<h3 id="analog-to-digital-converters-adc"><a class="header" href="#analog-to-digital-converters-adc">Analog-to-Digital Converters (ADC)</a></h3>
<p>There are a lot of digital sensors out there. You can use a protocol like I2C
and SPI to read them. But analog sensors also exist! These sensors just output a
voltage level that's proportional to the magnitude they are sensing.</p>
<p>The ADC peripheral can be used to convert that &quot;analog&quot; voltage level, say <code>1.25</code>
Volts, into a &quot;digital&quot; number, say in the <code>[0, 65535]</code> range, that the processor
can use in its calculations.</p>
<p>Again the <a href="https://docs.rs/embedded-hal/0.2.6/embedded_hal/adc/index.html"><code>embedded-hal</code> <code>adc</code> module</a> as well as the <a href="https://github.com/nrf-rs/nrf-hal"><code>nrf52-hal</code></a> got you covered.</p>
<h3 id="digital-to-analog-converters-dac"><a class="header" href="#digital-to-analog-converters-dac">Digital-to-Analog Converters (DAC)</a></h3>
<p>As you might expect a DAC is exactly the opposite of ADC. You can write some
digital value into a register to produce a voltage in the <code>[0, 3.3V]</code> range
(assuming a <code>3.3V</code> power supply) on some &quot;analog&quot; pin. When this analog pin is
connected to some appropriate electronics and the register is written to at some
constant, fast rate (frequency) with the right values you can produce sounds or
even music!</p>
<h3 id="real-time-clock-rtc"><a class="header" href="#real-time-clock-rtc">Real Time Clock (RTC)</a></h3>
<p>This peripheral can be used to track time in &quot;human format&quot;. Seconds, minutes,
hours, days, months and years. This peripheral handles the translation from
&quot;ticks&quot; to these human friendly units of time. It even handles leap years and
Daylight Save Time for you!</p>
<h3 id="other-communication-protocols"><a class="header" href="#other-communication-protocols">Other communication protocols</a></h3>
<ul>
<li>SPI, abstracted within the <a href="https://docs.rs/embedded-hal/0.2.6/embedded_hal/spi/index.html"><code>embedded-hal</code> <code>spi</code> module</a> and implemented by the <a href="https://github.com/nrf-rs/nrf-hal"><code>nrf52-hal</code></a></li>
<li>I2S, currently not abstracted within the <code>embedded-hal</code> but implemented by the <a href="https://github.com/nrf-rs/nrf-hal"><code>nrf52-hal</code></a></li>
<li>Ethernet, there does exist a small TCP/IP stack named <a href="https://github.com/smoltcp-rs/smoltcp"><code>smoltcp</code></a> which is implemented for some
chips but the ones on the micro:bit don't feature an Ethernet peripheral</li>
<li>USB, there is some experimental work on this, for example with the <a href="https://github.com/mvirkkunen/usb-device"><code>usb-device</code></a> crate</li>
<li>Bluetooth, there does exist an incomplete BLE stack named <a href="https://github.com/jonas-schievink/rubble"><code>rubble</code></a> which does support nrf chips.</li>
<li>SMBUS, neither abstracted in <code>embedded-hal</code> nor implemented by the <a href="https://github.com/nrf-rs/nrf-hal"><code>nrf52-hal</code></a> at the moment.</li>
<li>CAN, neither abstracted in <code>embedded-hal</code> nor implemented by the <a href="https://github.com/nrf-rs/nrf-hal"><code>nrf52-hal</code></a> at the moment</li>
<li>IrDA, neither abstracted in <code>embedded-hal</code> nor implemented by the <a href="https://github.com/nrf-rs/nrf-hal"><code>nrf52-hal</code></a> at the moment</li>
</ul>
<p>Different applications use different communication protocols. User facing
applications usually have a USB connector because USB is a ubiquitous
protocol in PCs and smartphones. Whereas inside cars you'll find plenty of CAN
&quot;buses&quot;. Some digital sensors use SPI, others use I2C and others, SMBUS.</p>
<p>If you happen to be interested in developing abstractions in the <code>embedded-hal</code> or
implementations of peripherals in general, don't be shy to open an issue in the HAL
repositories. Alternatively you could also join the <a href="https://matrix.to/#/#rust-embedded:matrix.org">Rust Embedded matrix channel</a>
and get into contact with most of the people who built the stuff from above.</p>
<h2 id="general-embedded-relevant-topics"><a class="header" href="#general-embedded-relevant-topics">General Embedded-Relevant Topics</a></h2>
<p>These topics cover items that are not specific to our device, or the hardware on
it. Instead, they discuss useful techniques that could be used on embedded
systems.</p>
<h3 id="gyroscopes"><a class="header" href="#gyroscopes">Gyroscopes</a></h3>
<p>As part of our Punch-o-meter exercise, we used the Accelerometer to measure
changes in acceleration in three dimensions. But there are other motion
sensors such as gyroscopes, which allows us to measure changes in &quot;spin&quot; in three
dimensions.</p>
<p>This can be very useful when trying to build certain systems, such as a robot
that wants to avoid tipping over. Additionally, the data from a sensor like a
gyroscope can also be combined with data from accelerometer using a technique
called Sensor Fusion (see below for more information).</p>
<h3 id="servo-and-stepper-motors"><a class="header" href="#servo-and-stepper-motors">Servo and Stepper Motors</a></h3>
<p>While some motors are used primarily just to spin in one direction or the other,
for example driving a remote control car forwards or backwards, it is sometimes
useful to measure more precisely how a motor rotates.</p>
<p>Our microcontroller can be used to drive Servo or Stepper motors, which allow
for more precise control of how many turns are being made by the motor, or
can even position the motor in one specific place, for example if we wanted to
move the arms of a clock to a particular direction.</p>
<h3 id="sensor-fusion"><a class="header" href="#sensor-fusion">Sensor fusion</a></h3>
<p>The micro:bit contains two motion sensors: an accelerometer and a magnetometer.
On their own these measure: (proper) acceleration and (the Earth's) magnetic field.
But these magnitudes can be &quot;fused&quot; into something more useful: a &quot;robust&quot; measurement
of the orientation of the board. Where robust means with less measurement error than
a single sensor would be capable of.</p>
<p>This idea of deriving more reliable data from different sources is known as
sensor fusion.</p>
<hr />
<p>So where to next? There are several options:</p>
<ul>
<li>You could check out the examples in the <a href="https://github.com/nrf-rs/microbit/"><code>microbit</code></a> board support crate. All those examples work for
the micro:bit board you have.</li>
</ul>
<ul>
<li>You could join the <a href="https://matrix.to/#/#rust-embedded:matrix.org">Rust Embedded matrix channel</a>, lots of people who contribute or work on embedded software
hang out there. Including for example the people who wrote the <code>microbit</code> BSP, the <code>nrf52-hal</code>, <code>embedded-hal</code> etc.</li>
</ul>
<ul>
<li>If you are looking for a general overview of what is available in Rust Embedded right now check out the <a href="https://github.com/rust-embedded/awesome-embedded-rust/">Awesome Rust Embedded</a>
list</li>
</ul>
<ul>
<li>You could check out <a href="https://rtic.rs">Real-Time Interrupt-driven Concurrency</a>. A very efficient preemptive multitasking framework
that supports task prioritization and dead lock free execution.</li>
</ul>
<ul>
<li>You could check out more abstractions of the <a href="https://github.com/rust-embedded/embedded-hal"><code>embedded-hal</code></a> project and maybe even try and write your own
platform agnostic driver based on it.</li>
</ul>
<ul>
<li>You could try running Rust on a different development board. The easiest way to get started is to
use the <a href="https://docs.rs/cortex-m-quickstart/0.3.1/cortex_m_quickstart/"><code>cortex-m-quickstart</code></a> Cargo project template.</li>
</ul>
<ul>
<li>You could try out <a href="https://mobile.twitter.com/japaricious/status/962770003325005824">this motion sensors demo</a>. Details about the implementation and
source code are available in <a href="http://blog.japaric.io/wd-1-2-l3gd20-lsm303dlhc-madgwick/">this blog post</a>.</li>
</ul>
<ul>
<li>You could check out <a href="http://blog.japaric.io/brave-new-io/">this blog post</a> which describes how Rust type system can
prevent bugs in I/O configuration.</li>
</ul>
<ul>
<li>You could check out <a href="http://blog.japaric.io">japaric's blog</a> for miscellaneous topics about embedded development with Rust.</li>
</ul>
<ul>
<li>You could join the <a href="https://github.com/rust-lang-nursery/embedded-wg/issues/39">Weekly driver initiative</a> and help us write generic drivers on top of the
<code>embedded-hal</code> traits and that work for all sorts of platforms (ARM Cortex-M, AVR, MSP430, RISCV,
etc.)</li>
</ul>
<div style="break-before: page; page-break-before: always;"></div><h1 id="general-troubleshooting"><a class="header" href="#general-troubleshooting">General troubleshooting</a></h1>
<h2 id="cargo-embed-problems"><a class="header" href="#cargo-embed-problems"><code>cargo-embed</code> problems</a></h2>
<p>Most <code>cargo-embed</code> problems are either related to not having installed the <code>udev</code>
rules properly (on Linux) or having selected the wrong chip configuration in <code>Embed.toml</code> so
make sure you got both of those right.</p>
<p>If the above does not work out for you, you can open an issue in the <a href="https://github.com/rust-embedded/discovery/issues"><code>discovery</code> issue tracker</a>.
Alternatively you can also visit the <a href="https://matrix.to/#/#rust-embedded:matrix.org">Rust Embedded matrix channel</a> or the <a href="https://matrix.to/#/#probe-rs:matrix.org">probe-rs matrix channel</a>
and ask for help there.</p>
<h2 id="cargo-problems"><a class="header" href="#cargo-problems">Cargo problems</a></h2>
<h3 id="cant-find-crate-for-core"><a class="header" href="#cant-find-crate-for-core">&quot;can't find crate for <code>core</code>&quot;</a></h3>
<h4 id="symptoms"><a class="header" href="#symptoms">Symptoms</a></h4>
<pre><code>   Compiling volatile-register v0.1.2
   Compiling rlibc v1.0.0
   Compiling r0 v0.1.0
error[E0463]: can't find crate for `core`

error: aborting due to previous error

error[E0463]: can't find crate for `core`

error: aborting due to previous error

error[E0463]: can't find crate for `core`

error: aborting due to previous error

Build failed, waiting for other jobs to finish...
Build failed, waiting for other jobs to finish...
error: Could not compile `r0`.

To learn more, run the command again with --verbose.
</code></pre>
<h4 id="cause"><a class="header" href="#cause">Cause</a></h4>
<p>You forgot to install the proper target for your microcontroller (<code>thumbv7em-none-eabihf</code> for v2
and <code>thumbv6m-none-eabi</code> for v1).</p>
<h4 id="fix"><a class="header" href="#fix">Fix</a></h4>
<p>Install the proper target.</p>
<pre><code class="language-console"># micro:bit v2
$ rustup target add thumbv7em-none-eabihf

# micro:bit v1
$ rustup target add thumbv6m-none-eabi
</code></pre>
<div style="break-before: page; page-break-before: always;"></div><h1 id="how-to-use-gdb"><a class="header" href="#how-to-use-gdb">How to use GDB</a></h1>
<p>Below are some useful GDB commands that can help us debug our programs. This assumes you have <a href="appendix/2-how-to-use-gdb/../../05-led-roulette/flash-it.html">flashed a program</a> onto your microcontroller and attached GDB to a <code>cargo-embed</code> session.</p>
<h2 id="general-debugging"><a class="header" href="#general-debugging">General Debugging</a></h2>
<blockquote>
<p><strong>NOTE:</strong> Many of the commands you see below can be executed using a short form. For example, <code>continue</code> can simply be used as <code>c</code>, or <code>break $location</code> can be used as <code>b $location</code>. Once you have experience with the commands below, try to see how short you can get the commands to go before GDB doesn't recognize them!</p>
</blockquote>
<h3 id="dealing-with-breakpoints"><a class="header" href="#dealing-with-breakpoints">Dealing with Breakpoints</a></h3>
<ul>
<li><code>break $location</code>: Set a breakpoint at a place in your code. The value of <code>$location</code> can include:
<ul>
<li><code>break *main</code> - Break on the exact address of the function <code>main</code></li>
<li><code>break *0x080012f2</code> - Break on the exact memory location <code>0x080012f2</code></li>
<li><code>break 123</code> - Break on line 123 of the currently displayed file</li>
<li><code>break main.rs:123</code> - Break on line 123 of the file <code>main.rs</code></li>
</ul>
</li>
<li><code>info break</code>: Display current breakpoints</li>
<li><code>delete</code>: Delete all breakpoints
<ul>
<li><code>delete $n</code>: Delete breakpoint <code>$n</code> (<code>n</code> being a number. For example: <code>delete $2</code>)</li>
</ul>
</li>
<li><code>clear</code>: Delete breakpoint at next instruction
<ul>
<li><code>clear main.rs:$function</code>: Delete breakpoint at entry of <code>$function</code> in <code>main.rs</code></li>
<li><code>clear main.rs:123</code>: Delete breakpoint on line 123 of <code>main.rs</code></li>
</ul>
</li>
<li><code>enable</code>: Enable all set breakpoints
<ul>
<li><code>enable $n</code>: Enable breakpoint <code>$n</code></li>
</ul>
</li>
<li><code>disable</code>: Disable all set breakpoints
<ul>
<li><code>disable $n</code>: Disable breakpoint <code>$n</code></li>
</ul>
</li>
</ul>
<h3 id="controlling-execution"><a class="header" href="#controlling-execution">Controlling Execution</a></h3>
<ul>
<li><code>continue</code>: Begin or continue execution of your program</li>
<li><code>next</code>: Execute the next line of your program
<ul>
<li><code>next $n</code>: Repeat <code>next</code> <code>$n</code> number times</li>
</ul>
</li>
<li><code>nexti</code>: Same as <code>next</code> but with machine instructions instead</li>
<li><code>step</code>: Execute the next line, if the next line includes a call to another function, step into that code
<ul>
<li><code>step $n</code>: Repeat <code>step</code> <code>$n</code> number times</li>
</ul>
</li>
<li><code>stepi</code>: Same as <code>step</code> but with machine instructions instead</li>
<li><code>jump $location</code>: Resume execution at specified location:
<ul>
<li><code>jump 123</code>: Resume execution at line 123</li>
<li><code>jump 0x080012f2</code>: Resume execution at address 0x080012f2</li>
</ul>
</li>
</ul>
<h3 id="printing-information"><a class="header" href="#printing-information">Printing Information</a></h3>
<ul>
<li><code>print /$f $data</code> - Print the value contained by the variable <code>$data</code>. Optionally format the output with <code>$f</code>, which can include:
<pre><code class="language-txt">x: hexadecimal
d: signed decimal
u: unsigned decimal
o: octal
t: binary
a: address
c: character
f: floating point
</code></pre>
<ul>
<li><code>print /t 0xA</code>: Prints the hexadecimal value <code>0xA</code> as binary (0b1010)</li>
</ul>
</li>
<li><code>x /$n$u$f $address</code>: Examine memory at <code>$address</code>. Optionally, <code>$n</code> define the number of units to display,
<code>$u</code> unit size (bytes, halfwords, words, etc.), <code>$f</code> any <code>print</code> format defined above
<ul>
<li><code>x /5i 0x080012c4</code>: Print 5 machine instructions staring at address <code>0x080012c4</code></li>
<li><code>x/4xb $pc</code>: Print 4 bytes of memory starting where <code>$pc</code> currently is pointing</li>
</ul>
</li>
<li><code>disassemble $location</code>
<ul>
<li><code>disassemble /r main</code>: Disassemble the function <code>main</code>, using <code>/r</code> to show the bytes that make up each instruction</li>
</ul>
</li>
</ul>
<h3 id="looking-at-the-symbol-table"><a class="header" href="#looking-at-the-symbol-table">Looking at the Symbol Table</a></h3>
<ul>
<li><code>info functions $regex</code>: Print the names and data types of functions matched by <code>$regex</code>, omit <code>$regex</code> to print all functions
<ul>
<li><code>info functions main</code>: Print names and types of defined functions that contain the word <code>main</code></li>
</ul>
</li>
<li><code>info address $symbol</code>: Print where <code>$symbol</code> is stored in memory
<ul>
<li><code>info address GPIOC</code>: Print the memory address of the variable <code>GPIOC</code></li>
</ul>
</li>
<li><code>info variables $regex</code>: Print names and types of global variables matched by <code>$regex</code>, omit <code>$regex</code> to print all global variables</li>
<li><code>ptype $data</code>: Print more detailed information about <code>$data</code>
<ul>
<li><code>ptype cp</code>: Print detailed type information about the variable <code>cp</code></li>
</ul>
</li>
</ul>
<h3 id="poking-around-the-program-stack"><a class="header" href="#poking-around-the-program-stack">Poking around the Program Stack</a></h3>
<ul>
<li><code>backtrace $n</code>: Print trace of <code>$n</code> frames, or omit <code>$n</code> to print all frames
<ul>
<li><code>backtrace 2</code>: Print trace of first 2 frames</li>
</ul>
</li>
<li><code>frame $n</code>: Select frame with number or address <code>$n</code>, omit <code>$n</code> to display current frame</li>
<li><code>up $n</code>: Select frame <code>$n</code> frames up</li>
<li><code>down $n</code>: Select frame <code>$n</code> frames down</li>
<li><code>info frame $address</code>: Describe frame at <code>$address</code>, omit <code>$address</code> for currently selected frame</li>
<li><code>info args</code>: Print arguments of selected frame</li>
<li><code>info registers $r</code>: Print the value of register <code>$r</code> in selected frame, omit <code>$r</code> for all registers
<ul>
<li><code>info registers $sp</code>: Print the value of the stack pointer register <code>$sp</code> in the current frame</li>
</ul>
</li>
</ul>
<h3 id="controlling-cargo-embed-remotely"><a class="header" href="#controlling-cargo-embed-remotely">Controlling <code>cargo-embed</code> Remotely</a></h3>
<ul>
<li><code>monitor reset</code>: Reset the CPU, starting execution over again</li>
</ul>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->


                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">

            </nav>

        </div>




        <script type="text/javascript">
            window.playground_copyable = true;
        </script>


        <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="searcher.js" type="text/javascript" charset="utf-8"></script>

        <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->

        <script type="text/javascript">
        window.addEventListener('load', function() {
            window.setTimeout(window.print, 100);
        });
        </script>

    </body>
</html>
